gpt4 book ai didi

vue.js - Vue Chart.js - 条形图上的简单点/线

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:00 26 4
gpt4 key购买 nike

我需要在我的 bar 图表上添加一条简单的点/垂直线,它具有动态 X 值,0 代表 Y 值。我需要的预览(红点):

enter image description here

绿色值是动态的。

我当前状态的预览:

enter image description here

其中 3.30 应该是点的 X 坐标 - [3.30, 0]。

我正在使用 Vue chart对于图表,我尝试创建一个 mixed一个带有 barscatterscatter 需要 type: 'linear' 因为它是 xAxis 不符合我对 bar 图表的需要。

所以我尝试了 chartjs-plugin-annotation它是接受“坐标”的 box 类型,但这里的问题是 X必须是 X 轴上的固定值(标签对象)。如果我将 X 轴设为 [3,0] 它会起作用,但如果有小数,例如 [3.5, 0],它就不起作用。


  // data
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 1,
stepSize: 0.1
}
}]
}
}

// computed
labels: [1, 2, 3, 4, 5, 6], // fixed value, there are always 6 bars
datasets: [
{
label: 'Values',
backgroundColor: '#f89098',
data: this.tableInputValues // array of decimal values
}
]

所以,我的问题是如何在 Chart.js 条形图上放置一个“简单”点或垂直线,其中点具有 X 轴的动态值 -> [动态值,0]。

仅供引用 - 关于 Expected value

最佳答案

据我所知,Vue Chart 使用 Canvas 工作(如 Demo page 所示)。
因此,我的建议是在 DOM 中检索表示图表的 Canvas 节点并动态写入所需的点。例如:

var c = document.getElementById("bar-chart");   //hereby assuming canvas named "bar-chart"
var ctx = c.getContext("2d");
ctx.fillStyle = "#ff0000"; //red color for the dot
ctx.beginPath();
let yPosition = c.height - 5; //fixed y position
let xPosition = 35; //that's the dynamic expected value
ctx.arc(xPosition, yPosition, 2.5, 0, 2 * Math.PI);
ctx.fill();

Here您会找到一个展示如何使用 Vue 实现该目标的演示。在这种情况下,您需要将代码包装在 afterDraw Hook 中的 Canvas 上绘制一个点。这个钩子(Hook)需要作为插件附加到图表组件,所以像这样:

...
mounted () {
//adding the plugin to draw the red dot
this.addPlugin({
id: 'chart-plugin',
afterDraw: function (chart) {
var c = chart.canvas;
var ctx = c.getContext("2d");
ctx.fillStyle = "#ff0000";
ctx.beginPath();
let xPosition = 742; //x positioning to be calculated according to your needs
let yPosition = c.height - 28;
ctx.arc(xPosition, yPosition, 3, 0, 2 * Math.PI);
ctx.fill();
}
});

//actual chart rendering
this.renderChart({
...
});
}
...

为了完整起见,here您会找到 Chart.js 插件 API 的所有可用 Hook 的列表。

关于vue.js - Vue Chart.js - 条形图上的简单点/线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53646391/

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