我已经创建了一个使用chartjs的组合双条形图。我的代码如下。条形组合二重图工作正常,但我要求为绿色条形图添加一条线,以连接所有顶部中点。我已经绘制了一些连接绿色图形的折线图,但是我面临的问题是,折线图点不在绿色条形图的顶部中间,如下所示。
谁能告诉我如何在条形图的顶部中间找到线条
html
<canvas id="canvas"></canvas>
js
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
type: 'bar',
label: "Visitor",
data: [10, 59, 340, 521, 450, 200, 195],
fill: false,
backgroundColor: "rgba(220,220,220,0.5)",
borderColor: '#71B37C',
hoverBackgroundColor: '#71B37C',
hoverBorderColor: '#71B37C'
}, {
type: 'bar',
label: "Visitor",
data: [200, 185, 590, 621, 250, 400, 95],
fill: false,
backgroundColor: '#71B37C',
borderColor: '#71B37C',
hoverBackgroundColor: '#71B37C',
hoverBorderColor: '#71B37C'
}, {
type:'line',
data: [200, 185, 590, 621, 250, 400, 95],
fill: false,
borderColor: '#EC932F',
backgroundColor: '#EC932F',
pointBorderColor: '#EC932F',
pointBackgroundColor: '#EC932F',
pointHoverBackgroundColor: '#EC932F',
pointHoverBorderColor: '#EC932F'
} ]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
tooltips: {
mode: 'label'
},
elements: {
line: {
fill: false
}
},
scales: {
xAxes: [{
display: true,
gridLines: {
display: false
},
labels: {
show: true,
}
}],
yAxes: [{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines:{
display: false
},
labels: {
show:true,
}
}, {
type: "linear",
display: true,
position: "right",
id: "y-axis-2",
gridLines:{
display: false
},
labels: {
show:true,
}
}]
}
}
});
};
要更改特定图表的显示,您必须编辑整个图表的配置。
在内部,您会发现需要更改特定图表(在您的情况下为折线图)所需的属性。
x
& y
属性,并将其存储在中 myBar.config.data.datasets[2].metaData[i]._model
( 我承认很难找到 )。
然后,您只需要将此代码添加到您的代码中(生成之后myBar
):
// For each value of your line chart ...
for (var i = 0; i < myBar.config.data.datasets[2].metaData.length; i++) {
// Get the bar width associated to this value
var barWidth = myBar.config.data.datasets[1].metaData[i]._model.width;
// Get the percentage that the bar is taking in the graph
var barPercentage = myBar.config.options.scales.xAxes[0].barPercentage;
// Add the width of the bar / (2*percentage) -- which is the half of the bar
myBar.config.data.datasets[2].metaData[i]._model.x += barWidth / (2*barPercentage);
// Also edit the controlPointNext and controlPointPrevious to change the bezier curve display
myBar.config.data.datasets[2].metaData[i]._model.controlPointNextX += barWidth / (2*barPercentage);
myBar.config.data.datasets[2].metaData[i]._model.controlPointPreviousX += barWidth / (2*barPercentage);
}
检查插栓的完整代码。
为了使图具有响应性,您将需要在Chart.js插件内部实现循环。
插件使您能够处理在创建,更新,渲染图形时触发的所有事件。
我们将特别编辑该afterUpdate
事件,该事件在每次更新时都会触发(例如,调整大小)。
Chart.pluginService.register({
afterUpdate: function(chart) {
// Loop in here
}
});
这是最终结果的另一个小提琴,它具有响应性。
请注意,条形图是在第一行之后绘制的(我不知道为什么),因此我不得不降低alpha
条形背景色的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句