reactjs - 0-10 分钟时间范围内的 React Victory 折线图
问题描述
可以使用一些帮助尝试使用 Victory 创建一个简单的折线图。
我正在尝试做的事情:
我基本上是在尝试创建一个显示过去 10 分钟随机数的折线图。我每 3 秒生成一个新的随机数,并将该随机数添加到折线图中。
所以 X 轴应该是从 0 分钟到 10 分钟,Y 轴应该是给定时间的实际 rand num。
我的主要问题是我对如何以 3 秒为间隔从 0 到 10 分钟创建 X 轴非常迷茫
到目前为止我所拥有的:
这是我到目前为止所做的代码沙箱,因此您可以尝试一下:https ://codesandbox.io/s/6wnzkz512n
主要Chart
成分:
import React from 'react'
import { VictoryChart, VictoryLine, VictoryAxis } from 'victory'
class Chart extends React.Component {
constructor() {
super()
this.state = {
data: []
}
}
// Add a new data point every 3 seconds
componentDidMount() {
this.getRandNum()
setInterval(this.getRandNum, 3000)
}
// get rand num from 1-5 along with current time,
// and add it to data. not sure if this is right approach
getRandNum = () => {
const newData = {
date: new Date(),
num: Math.floor(Math.random() * 5) + 1
}
this.setState({
data: [...this.state.data, newData]
})
}
render() {
return (
<VictoryChart width={600} height={470}>
<VictoryLine
style={{
data: { stroke: 'lime' }
}}
data={this.state.data}
x="date"
y="num"
/>
</VictoryChart>
)
}
}
解决方案
带有解决方案的代码沙箱:https ://codesandbox.io/s/989zx8v6v4
变化:
- 在状态中添加startTime
- state.data.date重命名为state.data.time并包含来自 stat 的秒数
- 在componentDidMount()中初始化
- getRandNum()以秒为单位计算时间差
- VictoryAxis 将X 轴格式化为“m:ss”
图表组件:
class Chart extends React.Component {
constructor() {
super();
this.state = {
data: [],
startTime: null
};
}
// Add a new data point every 3 seconds
componentDidMount() {
const startTime = new Date();
const time = 0;
const num = Math.floor(Math.random() * 5) + 1;
this.setState({ data: [{ time, num }], startTime });
setInterval(this.getRandNum, 3000);
}
// get rand num from 1-5 along with current time,
// and add it to data. not sure if this is right approach
getRandNum = () => {
const actualTime = new Date();
let num = Math.floor(Math.random() * 5) + 1;
let time = Math.round((actualTime - this.state.startTime) / 1000);
this.setState({
data: [...this.state.data, { time, num }]
});
};
render() {
return (
<VictoryChart width={600} height={470}>
<VictoryAxis dependentAxis />
<VictoryAxis
tickFormat={t =>
`${Math.floor(t / 60)}:${Math.round(t % 60)
.toString()
.padStart(2, "0")}`
}
/>
<VictoryLine
style={{
data: { stroke: "lime" }
}}
data={this.state.data}
x="time"
y="num"
/>
</VictoryChart>
);
}
}
推荐阅读
- ios - 滚动 UITableView 时 Google Ads SDK 60% 的 CPU 使用率
- python - Python-访问字典中的列表
- python - 创建一个多级饼图,其中外圆是 matplotlib 中内圆的子集
- ionic-framework - 在离子应用程序'模块''*''中导出到 excel 时生成错误没有导出的成员'
- typescript - 有没有办法只有一个 AWS APIGateway 请求来获取 AWS StepFunction 的输出?
- python - 将数据插入多个 SQL 表的 Python 脚本
- jquery - Newsignature 美国地图:悬停任何州时更改州填充
- javascript - 我的 Purge 命令有问题 (Discord.js)
- flutter - 颤振应用程序中的相机问题(> Android 不支持所选的 imageFormatGroup。默认为 yuv420)
- node.js - 动态发送剩余电子邮件节点js