gpt4 book ai didi

charts - 如何在Chart js中向数据集添加偏移量

转载 作者:行者123 更新时间:2023-12-04 22:19:24 25 4
gpt4 key购买 nike

我能够为 X 标签添加偏移量,但我想为数据集中的所有点添加偏移量。是否可以?

Chart

这是我正在使用的代码:

var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize : 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength:5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}}],
yAxes: [{
gridLines: {
display:false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});

我想将该偏移量应用于所有点,在图像中我刚刚向 JAN/DEC 添加了一个箭头,但我想将其应用于所有点。

我尝试添加一个空数据,问题是我不想显示第一个虚线网格。

enter image description here

有任何想法吗?提前致谢。

最佳答案

您可以使用 Chart.js 插件来实现这一点。它们让您可以处理在图表创建期间触发的特定事件( beforeInitafterUpdateafterDraw ...)并且也很容易实现:

Chart.pluginService.register({
afterUpdate: function(chart) {
// This will be triggered after every update of the chart
}
});

现在,您只需遍历数据集数据模型(用于绘制图表的属性)并添加所需的偏移量:

Chart.pluginService.register({
afterUpdate: function(chart) {
// We get the dataset and set the offset here
var dataset = chart.config.data.datasets[0];
var offset = 20;

// For every data in the dataset ...
for (var i = 0; i < dataset._meta[0].data.length; i++) {
// We get the model linked to this data
var model = dataset._meta[0].data[i]._model;

// And add the offset to the `x` property
model.x += offset;

// .. and also to these two properties
// to make the bezier curve fits the new graph
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
}
});

您可以看到您的示例正在运行 on this jsFiddle这是它的结果:

enter image description here

关于charts - 如何在Chart js中向数据集添加偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39700096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com