gpt4 book ai didi

javascript - 如何使用 ChartJS 在水平条形图上绘制垂直线?

转载 作者:太空狗 更新时间:2023-10-29 14:52:49 27 4
gpt4 key购买 nike

有许多扩展图表以包含水平和垂直线的示例。但是,我还没有找到用水平条形图绘制垂直线的方法。

  1. Horizontal line on horizontal line chart
  2. Vertical line onhorizontal line chart
  3. Horizontal line on vertical bar chart

没有像“水平条形图”选项那样的“垂直折线图”选项。如何将水平条形图与垂直线结合起来?

Chart.js documentation

结果将有一个条形数据集和一个线数据集,它们可以在使用相同轴的同一图表上使用,如下所示:

enter image description here

最佳答案

ChartJS 支持自定义插件。创建一个将从图表选项中读取新属性并在指定索引处绘制线条的插件。

See it on Plunkr

 //Create the plug in
var originalLineDraw = Chart.controllers.horizontalBar.prototype.draw;
Chart.helpers.extend(Chart.controllers.horizontalBar.prototype, {

draw: function () {
originalLineDraw.apply(this, arguments);

var chart = this.chart;
var ctx = chart.chart.ctx;

var index = chart.config.options.lineAtIndex;
if (index) {

var xaxis = chart.scales['x-axis-0'];
var yaxis = chart.scales['y-axis-0'];

var x1 = xaxis.getPixelForValue(index);
var y1 = yaxis.top;

var x2 = xaxis.getPixelForValue(index);
var y2 = yaxis.bottom;

ctx.save();
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.strokeStyle = 'red';
ctx.lineTo(x2, y2);
ctx.stroke();

ctx.restore();
}
}
});

//Set up the chart data
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};

//Load Chart
var ctx = $("#myChart");
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: {
//Set the index of the value where you want to draw the line
lineAtIndex: 60,
legend: {
display: false
}
}
});
    <canvas id="myChart"></canvas>

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js'></script>

<script src="horizontalBarPlugin.js"></script>
<script src="buildChart.js"></script>

关于javascript - 如何使用 ChartJS 在水平条形图上绘制垂直线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38256605/

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