javascript - 动态更新 Chart JS 中的一个点只会更新 y 值
问题描述
我有一个折线图,其中包含我试图在该线上设置动画的点。当我通过直接更改数据点的 x 和 y 值来更新图表时,只有画布上的 y 值会更新。但是,如果我在控制台中检查图表实例,数据点的 x 和 y 值确实会更新为新值。如果我使用工具提示检查画布上的数据点,您会看到只有 y 值正在更新。有任何想法吗?
// Data.
const dataset1 = [{ 'x': 29.0, 'y': 0.2686622628222965 },
{ 'x': 30.0, 'y': 1.6875564015713724 },
{ 'x': 31.0, 'y': 3.927335271321925 },
{ 'x': 32.0, 'y': 6.116677743682844 },
{ 'x': 33.0, 'y': 8.305688276805473 },
{ 'x': 34.0, 'y': 10.494369219774036 },
{ 'x': 35.0, 'y': 12.68059810657068 },
{ 'x': 36.0, 'y': 14.8711001192293 },
{ 'x': 37.0, 'y': 17.059239571115175 },
{ 'x': 38.0, 'y': 19.247118637561453 },
{ 'x': 39.0, 'y': 21.434670568612262 },
{ 'x': 40.0, 'y': 23.619730722191015 }];
// Options.
const getTsOptions = (tMin, tMax, tStep) => {
return {
scaleShowVerticalLines: false,
animation: false,
legend: { display: false },
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
display: false,
gridLines: {
color: "rgba(0,0,0,0)",
display: true
},
tickOptions: { showGridline: true }
}
],
yAxes: [
{
display: true,
gridLines: {
color: 'white',
display: true,
borderDash: [2],
lineWidth: 0.5,
drawBorder: false,
zeroLineColor: 'white'
},
ticks: {
min: tMin,
max: tMax,
stepSize: tStep,
fontColor: "white"
}
}
]
},
tooltips: { enabled: true }
};
};
// TS chart 1.
var myTSChart1 = new Chart(tsNode1, {
type: "line",
data: {
labels: dataset1.map(datapoint => datapoint.x),
datasets: [{
backgroundColor: "rgba(0,0,0,0)",
borderColor: "rgb(204, 204, 204)", // Line color
borderWidth: 3,
pointRadius: 0.0,
data: dataset1,
},
{
backgroundColor: "rgba(0,0,0,0)",
borderColor: "rgb(204, 204, 204)", // Line color
borderWidth: 3,
pointRadius: 5.0,
data: [{ x: 0, y: 0 }],
}]
},
options: getTsOptions(0, 25, 5)
});
在一个循环中,更新程序:
myTSChart1.data.datasets[1].data[0].x = newTime;
myTSChart1.data.datasets[1].data[0].y = newVelocity;
myTSChart1.update();
编辑
我做了一些更多的调试 - 如果我将 x 值四舍五入到标签中的值,它将更新。我仍然很困惑为什么我不能绘制一个值,比如 x 值为 35.345345 ......
解决方案
好吧,我猜chart.js 不喜欢将数据点更新为不在原始实例中的标签,除非您使用新的chart.js 时间刻度。所以我所做的是确保我预期数据点采用的所有值在标签中都有它们的 x 值。可能有更优雅的方式来做到这一点,但这是我现在的技巧。
推荐阅读
- winforms - 赢表格。如何使用 PrintDocument 以英寸或厘米为单位的精确坐标进行打印
- algorithm - 复杂度为 O(n) 的二维数组中的寻峰算法
- python - 单个页面上的多个 Django 表单
- c# - 当我单击 CheckBox 时,Wpf PasswordBox 必须显示字符
- c# - Entity Framework Core:将上传的文件保存到连接表
- spring - Spring Websocket:如何更新和反映 MessageBrokerRegistry 对象在运行时的变化?
- r - R / stringr:拆分字符串,但在输出中保留分隔符
- pytest - Moto 测试没有引发适当的异常
- cocoa - 在 TableView 单元内更改 NSTextField 光标颜色
- php - 使用刀片的 foreach 数组