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

Chart.js - draw horizontal line in Bar Chart (type bar)

本文关键字:绘制 水平线 Bar 类型 js- 条形图 Chart      更新时间:2023-09-26

晚上好,我想用Chart.js.在条形图上画一条水平线

我读了问题Chart.js-画水平线,但我不能在条形图上画线,正如折线图的实现所示。

我的代码被实现到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
});

并且它将能够绘制水平线,从而获得以下形式的图形:https://i.stack.imgur.com/QlOKG.png

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库的URL更改为:http://www.chartjs.org/assets/Chart.min.js

并从小提琴上删除了https。

在2021 chart.js版本中,它是这样使用的。

import {  Chart } from 'react-chartjs-2';
import annotationPlugin from "chartjs-plugin-annotation";
Chart.register([annotationPlugin]);
return (
  options={{
   
              annotations: {
              myHorizontalLine: {
                type: "line",
                scaleID: "y",
                borderWidth: 3,
                borderColor: "#333333",
                value: 100,
                borderDash: [8, 8],
                label: {
                  font: {
                    weight: "normal"
                  },
                  rotation: "auto",
                  enabled: true
                }
              }
            }
}}
)