【发布时间】: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