我有一个像这样的条形图
我需要在下面绘制水平虚线
我正在使用图表js来创建此图表。请帮助我画出这条基线。
var ctx = document.getElementById("baseLinebar");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["25", "60", "15", "30"],
datasets: [{
data: [25, 60, 15, 30],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
display:false
},
barThickness:40
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
});
答案 0 :(得分:5)
我们在这里使用horizonalLinePlugin
并将其注册到Chart pluginService
。您可以在horizontalLine
中使用option
作为config
的属性。使用此fiddle
<强> JS 强>
var config = {
type: 'bar',
data: {
labels: ["25", "60", "15", "30"],
datasets: [{
data: [25, 60, 15, 30],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
]
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
display: true
},
barThickness: 40,
stacked: true
}],
yAxes: [{
gridLines: {
display: true
},
stacked: true
}]
},
horizontalLine: [{
y: 50,
style: "rgba(255, 0, 0, .4)",
text: "max"
}, {
y: 15,
text: "min"
}]
}
};
;
var ctx = document.getElementById("canvas");
var horizonalLinePlugin = {
afterDraw: function (chartInstance) {
var yScale = chartInstance.scales["y-axis-0"];
var canvas = chartInstance.chart;
var ctx = canvas.ctx;
var index;
var line;
var style;
if (chartInstance.options.horizontalLine) {
for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
line = chartInstance.options.horizontalLine[index];
if (!line.style) {
style = "rgba(169,169,169, .6)";
} else {
style = line.style;
}
if (line.y) {
yValue = yScale.getPixelForValue(line.y);
} else {
yValue = 0;
}
ctx.lineWidth = 3;
if (yValue) {
ctx.beginPath();
ctx.moveTo(0, yValue);
ctx.lineTo(canvas.width, yValue);
ctx.strokeStyle = style;
ctx.stroke();
}
if (line.text) {
ctx.fillStyle = style;
ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
}
}
return;
};
}
};
Chart.pluginService.register(horizonalLinePlugin);
var myChart = new Chart(ctx, config);
答案 1 :(得分:0)
试试这样。
Chart.js确实有混合图表。
文档:http://www.chartjs.org/docs/#chart-configuration-mixed-chart-types
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['25', '60', '45'],
datasets: [
{
type: 'line',
label: 'Baseline',
data: [15, 15, 15 ]
},
{
type: 'bar',
label: 'Marks',
data: [25, 60, 45],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
]
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
&#13;
.container {
width: 80%;
margin: 15px auto;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script>
<div class="container">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
&#13;