【问题标题】:How to hide the legend in chart.js in a react project?如何在 react 项目中隐藏 chart.js 中的图例?
【发布时间】:2021-10-08 00:46:54
【问题描述】:

我正在尝试隐藏使用 Chart.js 创建的图表的图例。

根据官方文档(https://www.chartjs.org/docs/latest/configuration/legend.html),要隐藏图例,options.display对象的display属性必须设置为false

我尝试过以下方式:

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

但是不行,我的传奇还在。我什至尝试过这种其他方式,但不幸的是,没有成功。

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

这是我的完整代码。

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;

有人可以帮我吗?提前谢谢!

PD:也许对尝试找到解决方案很有用,但我的图例文本中出现“未定义”,当我尝试像这样更改文本时,文本图例仍显示为“Undefindex”。

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

【问题讨论】:

    标签: javascript reactjs chart.js


    【解决方案1】:

    如文档中所述,您将配置图例的命名空间链接为:options.plugins.legend,如果您将其放在那里,它将起作用:

    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>

    另一方面,您的选项对象的很大一部分是错误的,当您使用 v3 时,它是 V2 语法,请查看migration guide

    您在图例中得到 undefined 作为文本的原因是因为您没有在数据集中提供任何 label 参数。

    【讨论】:

    • 你认为我可以降级我的图表 js 的版本吗?编辑我的package-lock.json 文件就足够了吗? @LeeLenalee
    • 是的,但您需要通过将数字设置为 2.9.4 在您的普通 package.json 文件中对其进行编辑,然后再次运行您的安装命令。您也可以卸载chart.js,然后运行安装命令,但指定版本如下:npm i chart.js@2.9.4
    【解决方案2】:

    在图表组件中导入您的选项值,如下所示:

    const options = {
        legend: {
          display: false
        }
    };
    
    <Line data={data} options={options} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-01
      • 2020-09-23
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多