最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to hide the legend in chart.js in a react project? - Stack Overflow

programmeradmin0浏览0评论

I am trying to hide the legend of my chart created with Chart.js.

According to the official documentation (.html), to hide the legend, the display property of the options.display object must be set to false.

I have tried to do it in the following way:

const options = {
    legend: {
        display: false,
    }
};

But it doesn't work, my legend is still there. I even tried this other way, but unfortunately, without success.

const options = {
    legend: {
        display: false,
            labels: {
                display: false
            }
        }
    }
};

This is my full code.

import React, { useEffect, useState } from 'react';
import { Line } from "react-chartjs-2";
import numeral from 'numeral';

const options = {
    legend: {
        display: false,
    },
    elements: {
        point: {
            radius: 1,
        },
    },
    maintainAspectRatio: false,
    tooltips: {
        mode: "index",
        intersect: false,
        callbacks: {
            label: function (tooltipItem, data) {
                return numeral(tooltipItem.value).format("+0,000");
            },
        },
    },
    scales: {
        xAxes: [
            {
                type: "time",
                time: {
                    format: "DD/MM/YY",
                    tooltipFormat: "ll",
                },
            },
        ],
        yAxes: [
            {
                gridLines: {
                    display: false,
                },
                ticks: {
                    callback: function(value, index, values) {
                        return numeral(value).format("0a");
                    },
                },
            },
        ],
    },
};

const buildChartData = (data, casesType = "cases") => {
    let chartData = [];
    let lastDataPoint;

    for(let date in data.cases) {
        if (lastDataPoint) {
            let newDataPoint = {
                x: date,
                y: data[casesType][date] - lastDataPoint
            }
            chartData.push(newDataPoint);
        }
        lastDataPoint = data[casesType][date];
    }
    return chartData;
};

function LineGraph({ casesType }) {

    const [data, setData] = useState({});

    useEffect(() => {
        const fetchData = async() => {
            await fetch(";)
            .then ((response) => {
                return response.json();
            })
            .then((data) => {
                let chartData = buildChartData(data, casesType);
                setData(chartData);
            });
        };
        fetchData();
    }, [casesType]);

    return (
        <div>
            {data?.length > 0 && (
            <Line 
                data={{
                    datasets: [
                        {
                            backgroundColor: "rgba(204, 16, 52, 0.5)",
                            borderColor: "#CC1034",
                            data: data
                        },
                    ],
                }}
                options={options}
            />
            )}
        </div>
    );
}

export default LineGraph;

Could someone help me? Thank you in advance!

PD: Maybe is useful to try to find a solution, but I get 'undefined' in the text of my legend and when I try to change the text like this, the text legend still appearing as 'Undefindex'.

const options = {
    legend: {
        display: true,
        text: 'Hello!'
    }
};

I am trying to hide the legend of my chart created with Chart.js.

According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options.display object must be set to false.

I have tried to do it in the following way:

const options = {
    legend: {
        display: false,
    }
};

But it doesn't work, my legend is still there. I even tried this other way, but unfortunately, without success.

const options = {
    legend: {
        display: false,
            labels: {
                display: false
            }
        }
    }
};

This is my full code.

import React, { useEffect, useState } from 'react';
import { Line } from "react-chartjs-2";
import numeral from 'numeral';

const options = {
    legend: {
        display: false,
    },
    elements: {
        point: {
            radius: 1,
        },
    },
    maintainAspectRatio: false,
    tooltips: {
        mode: "index",
        intersect: false,
        callbacks: {
            label: function (tooltipItem, data) {
                return numeral(tooltipItem.value).format("+0,000");
            },
        },
    },
    scales: {
        xAxes: [
            {
                type: "time",
                time: {
                    format: "DD/MM/YY",
                    tooltipFormat: "ll",
                },
            },
        ],
        yAxes: [
            {
                gridLines: {
                    display: false,
                },
                ticks: {
                    callback: function(value, index, values) {
                        return numeral(value).format("0a");
                    },
                },
            },
        ],
    },
};

const buildChartData = (data, casesType = "cases") => {
    let chartData = [];
    let lastDataPoint;

    for(let date in data.cases) {
        if (lastDataPoint) {
            let newDataPoint = {
                x: date,
                y: data[casesType][date] - lastDataPoint
            }
            chartData.push(newDataPoint);
        }
        lastDataPoint = data[casesType][date];
    }
    return chartData;
};

function LineGraph({ casesType }) {

    const [data, setData] = useState({});

    useEffect(() => {
        const fetchData = async() => {
            await fetch("https://disease.sh/v3/covid-19/historical/all?lastdays=120")
            .then ((response) => {
                return response.json();
            })
            .then((data) => {
                let chartData = buildChartData(data, casesType);
                setData(chartData);
            });
        };
        fetchData();
    }, [casesType]);

    return (
        <div>
            {data?.length > 0 && (
            <Line 
                data={{
                    datasets: [
                        {
                            backgroundColor: "rgba(204, 16, 52, 0.5)",
                            borderColor: "#CC1034",
                            data: data
                        },
                    ],
                }}
                options={options}
            />
            )}
        </div>
    );
}

export default LineGraph;

Could someone help me? Thank you in advance!

PD: Maybe is useful to try to find a solution, but I get 'undefined' in the text of my legend and when I try to change the text like this, the text legend still appearing as 'Undefindex'.

const options = {
    legend: {
        display: true,
        text: 'Hello!'
    }
};

Share Improve this question edited Aug 2, 2021 at 17:03 Caín asked Aug 2, 2021 at 16:58 CaínCaín 3311 gold badge3 silver badges11 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

in the newest versions this code works fine

const options = {
    plugins: {
      legend: {
        display: false,
      },
    },
  };
return <Doughnut data={data} options={options} />;

As described in the documentation you linked the namespace where the legend is configured is: options.plugins.legend, if you put it there it will work:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        display: false
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>

On another note, a big part of your options object is wrong, its in V2 syntax while you are using v3, please take a look at the migration guide

Reason why you get undefined as text in your legend is, is because you dont supply any label argument in your dataset.

Import your options value inside the charts component like so:

const options = {
    legend: {
      display: false
    }
};

<Line data={data} options={options} />
发布评论

评论列表(0)

  1. 暂无评论