Fermer

février 29, 2024

Création d’une courbe en cloche à l’aide de React-Chartjs-2

Création d’une courbe en cloche à l’aide de React-Chartjs-2


Introduction

React-Chartjs-2 ou Chartjs-2 est une puissante bibliothèque de graphiques. Nous pouvons facilement créer des lignes, des barres et des diagrammes circulaires, mais il ne fournit aucune fonctionnalité directe pour créer une courbe en cloche. Dans cet article, nous allons apprendre à créer une courbe en cloche à l’aide de React-Chartjs-2 en utilisant le composant « Line » correspondant.

Avant de commencer à écrire, nous devons installer et importer chartjs et réagir-chartjs-2 :

import {  Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Filler, Tooltip, Legend } from "chart.js";

import { Line } from "react-chartjs-2";

Ensuite, nous devrons enregistrer notre carte :

ChartJS.register(

    CategoryScale,

    LinearScale,

    PointElement,

    LineElement,

    Title,

    Tooltip,

    Legend,

    Filler,

    annotationPlugin // should be imported from "chartjs-plugin-annotation" only if we want to show values on graph (in our case here, percentage of data falling in each section)

);

Création de la fonction Export :

  1. Ajouter des valeurs de données: Dans notre fonction d’export, créez un état pour enregistrer les données qui doivent être affichées sur la carte. Si notre courbe en cloche doit être divisée en « n » sections, alors l’état aura des valeurs « n+1 », où la première valeur sera toujours 0.

Pour 5 volets :

    const [ratingsData, setRatingsData] = useState([0,10,25,59,20,10]);

2. Ajouter des options pour le graphique :

const options = {

        responsive: true,

        plugins: {

            tooltip: { enabled: false },

            hover: { mode: null },

            legend: {

                position: "top"

            },

            title: {

                display: true,

                text: "",

            },

            annotation: {

                clip: false,

                annotations: {

                    label1: {

                        type: 'label',

                        display: true,

                        xValue: 1,

                        yValue: ratingsData[1] + 20,

                        backgroundColor: 'rgba(255,255,255)',

                        content: [ratingsData[1] ? `${ratingsData[1]}%` : ''],

                        font: {

                            size: 9

                        },

                    },

                    label2: {

                        type: 'label',

                        display: true,

                        xValue: 3,

                        yValue: ratingsData[2] + 20,

                        backgroundColor: 'rgba(255,255,255)',

                        content: [ratingsData[2] ? `${ratingsData[2]}%` : ''],

                        font: {

                            size: 9

                        }

                    },

                    label3: {

                        type: 'label',

                        display: true,

                        xValue: 5,

                        yValue: ratingsData[3] + 20,

                        backgroundColor: 'rgba(255,255,255)',

                        content: [ratingsData[3] ? `${ratingsData[3]}%` : ''],

                        font: {

                            size: 9

                        }

                    },

                    label4: {

                        type: 'label',

                        display: true,

                        xValue: 7,

                        yValue: ratingsData[4] + 20,

                        backgroundColor: 'rgba(255,255,255)',

                        content: [ratingsData[4] ? `${ratingsData[4]}%` : ''],

                        font: {

                            size: 9

                        }

                    },

                    label5: {

                        type: 'label',

                        display: true,

                        xValue: 9,

                        yValue: ratingsData[5] + 20,

                        backgroundColor: 'rgba(255,255,255)',

                        content: [ratingsData[5] ? `${ratingsData[5]}%` : ''],

                        font: {

                            size: 9

                        }

                    }

                },

            },

            datalabels: {

                display: false,

            },

        tension: 0.4,

        scales: {

            x: {

                grid: {

                    display: false

                },

                title: {

                    padding: { top: 35, left: 0, right: 0, bottom: 0 },

                    display: true,

                    text: 'Normal Company Wide Ratings',

                    font: {

                        weight: 'bold',

                        size: 12

                    },

                },

                ticks: {

                    font: {

                        weight: 'bold',

                        size: 9

                    },

                }

            },

            y: {

                grid: {

                    display: false

                },

                title: {

                    display: true,

                    text: 'Number of Newers',

                    font: {

                        weight: 'bold',

                        size: 12

                    },

                },

                ticks: {

                    display: false

                },

            }

        },

    };

3. Ajouter des étiquettes : Pour ajouter des étiquettes sur l’axe des X, créez un tableau de « n » éléments (avec un tableau imbriqué si une nouvelle ligne est requise)

const labels =

        ["",

            [[1], ['Needs'], [' Improvement']],

            "",

            [[2], ['Below'], [' Expectations']],

            "",

            [[3], ['Met'], [' Expectations']],

            "",

            [[4], ['Exceeded'], [' Expectations']],

            "",

            [[5], ['Outstanding']],

            ""];

4. Créez des points moyens à tracer sur un graphique : Pour créer une courbe, nous avons besoin d’au moins n*2 points sur le graphique, ce qui peut être fait en créant des valeurs moyennes.

const getAverageValue = (arr, index) => {

        let w = 0, x, y, z = 0;

        x = arr[index]

        y = arr[index + 1]

        return x > y ? (y + ((x - y) / 2)) : (x + ((y - x) / 2))

    }
const labels1 =

    {

        "0": getAverageValue(ratingsData, 0),

        "0.5": ratingsData[1],

        "1": getAverageValue(ratingsData, 1),

        "1.5": ratingsData[2],

        "2": getAverageValue(ratingsData, 2),

        "2.5": ratingsData[3],

        "3": getAverageValue(ratingsData, 3),

        "3.5": ratingsData[4],

        "4": getAverageValue(ratingsData, 4),

        "4.5": ratingsData[5],

        "5": 0

    }

5. Remplir le graphique avec des couleurs: Créez un tableau pour ajouter des couleurs qui doivent être remplies dans toutes les sections du graphique.

var colors = [

        "rgba(241,91,105,1)",

        "rgba(254,226,130,1)",

        "rgba(31,158,107,1)",

        "rgba(79,162,255,1)",

        "rgba(64,56,255,1)",

    ];

6. Créer un ensemble de données pour le graphique

let DataSet = [

        {

            label: ``,

            data: [

                labels1['0'],

                labels1['0.5'],

                labels1['1'],

            ],

            fill: {

                target: "origin",

                above: colors[0],

            },

            backgroundColor: 'rgb(255,255,255,0)',

            borderColor: 'rgb(255,255,255,0)',

        },

        {

            label: ``,

            data: [

                labels1['0'],

                labels1['0.5'],

                labels1['1'],

                labels1['1.5'],

                labels1['2'],

            ],

            fill: {

                target: "origin",

                above: colors[1],

            },

            backgroundColor: 'rgb(255,255,255,0)',

            borderColor: 'rgb(255,255,255,0)',

        },

        {

            label: ``,

            data: [

                labels1['0'],

                labels1['0.5'],

                labels1['1'],

                labels1['1.5'],

                labels1['2'],

                labels1['2.5'],

                labels1['3'],

            ],

            fill: {

                target: "origin",

                above: colors[2],

            },

            backgroundColor: 'rgb(255,255,255,0)',

            borderColor: 'rgb(255,255,255,0)',

        },

        {

            label: ``,

            data: [

                labels1['0'],

                labels1['0.5'],

                labels1['1'],

                labels1['1.5'],

                labels1['2'],

                labels1['2.5'],

                labels1['3'],

                labels1['3.5'],

                labels1['4']

            ],

            fill: {

                target: "origin",

                above: colors[3],

            },

            backgroundColor: 'rgb(255,255,255,0)',

            borderColor: 'rgb(255,255,255,0)',

        },

        {

            label: ``,

            data: [

                labels1['0'],

                labels1['0.5'],

                labels1['1'],

                labels1['1.5'],

                labels1['2'],

                labels1['2.5'],

                labels1['3'],

                labels1['3.5'],

                labels1['4'],

                labels1['4.5'],

                labels1['5'],

            ],

            fill: {

                target: "origin",

                above: colors[4],

            },

            backgroundColor: 'rgb(255,255,255,0)',

            borderColor: 'rgb(255,255,255,0)',

        },

    ];

7. Combiner des étiquettes et des ensembles de données: Créez un objet pour les étiquettes et les ensembles de données. Transmettez ensuite les options et cet objet de données à notre graphique linéaire

const data = {

        labels: labels,

        datasets: DataSet,

    };

8. Retour ci-dessous depuis notre fonction export :

<Line options={options} data={data} ref={chartRef}

Conclusion

Après la dernière étape, notre graphique ressemblera à ci-dessous :

VOUS TROUVEZ CECI UTILE ? PARTAGEZ-LE






Source link