首页 文章

Chart.js绘制带有限制线的堆积条形图

提问于
浏览
0

我想使用Chart.js在图表中绘制一条水平线 . 但是我无法做到 .

我发现这个example但是我've had trouble converting it to a bar chart as it'使用点来确定放置线的位置和条形图似乎没有使用"points"

var data = {
    labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
    datasets: [{
        data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
    }]
};

var ctx = document.getElementById("LineWithLine").getContext("2d");

Chart.types.Line.extend({
    name: "LineWithLine",
    initialize: function () {
        Chart.types.Line.prototype.initialize.apply(this, arguments);
    },
    draw: function () {
        Chart.types.Line.prototype.draw.apply(this, arguments);
        
        var point = this.datasets[0].points[this.options.lineAtIndex]
        var scale = this.scale
        console.log(this);

        // draw line
        this.chart.ctx.beginPath();
        this.chart.ctx.moveTo(scale.startPoint+12, point.y);
        this.chart.ctx.strokeStyle = '#ff0000';
        this.chart.ctx.lineTo(this.chart.width, point.y);
        this.chart.ctx.stroke();
        
        // write TODAY
        this.chart.ctx.textAlign = 'center';
        this.chart.ctx.fillText("TODAY", scale.startPoint + 35, point.y+10);
    }
});

new Chart(ctx).LineWithLine(data, {
    datasetFill : false,
    lineAtIndex: 2
});
<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<div>
    <canvas id="LineWithLine" width="600" height="400"></canvas>
</div>

在Chart.js 2中有更好的方法吗?也许使用折线图和条形图组合还是有点矫枉过正?

希望你们能帮助我解决这个问题,我已经使用CSS和Javascript创建了这个图表,如下所示:

enter image description here

在这个例子中,限制是一个负值,所以它已经将自己绘制在实际线下面,这可能会令人困惑,但主要的是线被绘制在我选择的值上 . :)

1 回答

  • 1

    如果您仍然遇到此问题,请查看以下关于drawing a custom horizontal line in Chart.js 2的问题

    在我链接的queston的答案中,它被定义为chart.js中的一个新插件(Chart.js ' site) allowing you to draw a bar chart and a custom line. There'中的更多信息也是一个jsfiddle以更好地理解插件是如何工作的

相关问题