折线图不适用于 time chart.js 类型
Posted
技术标签:
【中文标题】折线图不适用于 time chart.js 类型【英文标题】:Line chart doesn't work with type time chart.js 【发布时间】:2020-11-17 19:41:00 【问题描述】:我将 chart.js 与 React 一起使用,但我无法弄清楚为什么折线图不适用于 type: 'time'
,也许我可能遗漏了一些东西:
Chart.js CodeSandbox
import React from "react";
import Line from "react-chartjs-2";
const startDate = new Date(2020, 4, 20);
const json = '"responses":["count":"73","rows":["values":["1"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["0"],"values":["1"],"values":["6"],"values":["7"],"values":["5"],"values":["8"],"values":["9"],"values":["2"],"values":["1"],"values":["1"],"values":["1"],"values":["6"],"values":["3"],"values":["0"],"values":["20"],"values":["9"],"values":["3"],"values":["2"],"values":["1"],"values":["13"],"values":["3"],"values":["13"],"values":["13"],"values":["7"],"values":["12"],"values":["0"]]]';
const values = JSON.parse(json).responses[0].rows.map(row => row.values[0]);
const options =
legend:
display: false
,
hover:
mode: "index",
intersect: false,
animationDuration: 0
,
scales:
yAxes: [ position: "right" ],
xAxes: [
gridLines: display: false ,
type: "time",
time:
parser: "MMM D",
unit: "day",
unitStepSize: 5,
displayFormats:
day: "MMM D"
,
ticks:
min: startDate, //May 20
max: new Date()
]
,
tooltips:
mode: "x-axis"
;
const data =
datasets: [
label: "data",
fill: false,
data: values,
backgroundColor: "pink",
borderWidth: 2,
lineTension: 0,
borderColor: "pink",
hoverBorderWidth: 2,
pointBorderColor: "rgba(0, 0, 0, 0)",
pointBackgroundColor: "rgba(0, 0, 0, 0)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "pink",
showLine: true
]
;
const LineChart = () =>
return (
<div style= maxWidth: 1024, margin: "32px auto" >
<Line data=data options=options />
</div>
);
;
export default LineChart;
【问题讨论】:
【参考方案1】:你应该像这样生成特定的数据集:
const values = JSON.parse(json).responses[0].rows.map((row, index) =>
let date = new Date(2020, 4, 20);
date.setDate(startDate.getDate() + index)
return
y: row.values[0],
x: date
;
);
example
【讨论】:
以上是关于折线图不适用于 time chart.js 类型的主要内容,如果未能解决你的问题,请参考以下文章
Chart.js - 如何为随时间发生的大量数据创建自动缩放折线图