Chart.js - 在条形图中绘制水平线(类型栏)

时间:2016-07-25 06:56:26

标签: javascript jquery chart.js

晚上好,我想使用Chart.js在图表条形图上绘制一条水平线。

我阅读了问题Chart.js - draw horizontal line,我无法在条形图上绘制线条,如图所示是折线图的实现。

我的代码已实施到jsfiddle

HTML

<div>
  <canvas id="ctx"></canvas>
</div>

JS

var data = {
    labels: ["Docente 1", "Docente 2", "Docente 3", "Docente 4", "Docente 5", "Docente 6", "Docente 7"],
    datasets: [
        {
            label: "Semestre 2017-I",
            borderWidth: 1,
            data: [3.65, 2.59, 1.80, 2.81, 0.56, 0.55, 3.40]
        }
    ]
};            

var ctx = document.getElementById("ctx");

var myBarChart = new Chart(ctx, {
   type: 'bar',
   data: data
});

它将能够绘制水平线,获得形式的图形: http://i.stack.imgur.com/QlOKG.png

1 个答案:

答案 0 :(得分:3)

<强> HTML:

<div>
  <canvas id="ctx" width="600" height="400"></canvas>
</div>

<强> JS:

var data = {
                labels: ["Docente 1", "Docente 2", "Docente 3", "Docente 4", "Docente 5", "Docente 6", "Docente 7"],
                datasets: [
                    {
                        label: "Semestre 2017-I",
                        borderWidth: 1,
                        data: [3.65, 2.59, 1.80, 2.81, 0.56, 0.55, 3.40]
                    }
                ]
            };            

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

Chart.types.Bar.extend({
    name: "BarWithLine",
    initialize: function () {
        Chart.types.Bar.prototype.initialize.apply(this, arguments);
    },
    draw: function () {
        Chart.types.Bar.prototype.draw.apply(this, arguments);

        var lineHeight = 2; // <----

        // draw line
        this.chart.ctx.beginPath();
        this.chart.ctx.moveTo(0, this.scale.calculateY(lineHeight));
        this.chart.ctx.strokeStyle = '#ff0000';
        this.chart.ctx.lineTo(this.chart.width, this.scale.calculateY(lineHeight));
        this.chart.ctx.stroke();
    }
});

var myBarChart = new Chart(ctx).BarWithLine(data, {
  type: 'bar',
  data: data
});

这是小提琴:http://jsfiddle.net/zk9oc4c9/

重要说明:我将Chart.js库网址更改为: http://www.chartjs.org/assets/Chart.min.js

从小提琴中删除了https。