Jos*_*hua 8 momentjs reactjs chart.js react-chartjs-2
R/python 用户,javascript 新手。我正在尝试做一些我认为很简单的事情,即在 React 中使用 Chart-js 制作一个基本的时间序列图表。
我似乎无法让轴正常工作,这可能是一个非常基本的错误,但我似乎找不到任何有关如何在反应中执行此操作的文档。我的示例通常在 html/js 中运行,但在 React 中不起作用?React-chartjs-2 的文档是很简单的。
我想要一个折线图,其中 X 轴按日期缩放(我的数据是间隔不均匀的时间序列数据)。我认为你需要时间来做到这一点,但我得到的只是堆积到 1 个点上的数据(正确的 y 值,但所有值的 x 值均为零)。
我在codesandbox中包含了一个最小示例的链接,它基于react-chart-js 中的Line 示例中的示例。
应用程序.tsx
import React from "react";
import "chartjs-adapter-moment";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { Chart } from "react-chartjs-2";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
export const options = {
response: true,
scales: {
xAxes: [
{
type: "time",
time: {
unit: "day"
}
}
]
}
};
const values = [
{
x: new Date("2020-01-01"),
y: 100.2
},
{
x: new Date("2020-01-02"),
y: 102.2
},
{
x: new Date("2020-01-03"),
y: 105.3
},
{
x: new Date("2020-01-11"),
y: 104.4
}
];
export const data = {
datasets: [
{
data: values
}
]
};
export function App() {
return <Line options={options} data={data} />;
}
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/affectionate-hopper-uiqvz?file=/App.tsx
Lee*_*lee 11
这在正常情况下也不起作用,这是因为当您使用 V3 时,您的比例配置是 V2 样式。
在 v3 中,每个比例都是它自己的对象,其中键是比例 ID,因此不再有数组。将您的配置更改为此将使其正常工作:
options: {
scales: {
x: {
type: 'time'
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您还需要导入并注册时间刻度,而不是 x 轴的类别刻度。
import {
Chart as ChartJS,
TimeScale, //Import timescale instead of category for X axis
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
} from "chart.js";
import { Chart } from "react-chartjs-2";
ChartJS.register(
TimeScale, //Register timescale instead of category for X axis
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5896 次 |
最近记录: |