Chartjs:y轴上的自定义文本在特定级别

时间:2018-03-02 21:39:42

标签: chart.js

有没有办法将自定义文本添加到使用Chartjs创建的图表的y轴的某个级别?

这样的事情:

enter image description here

我已经检查过thick configuration options,但无法找到任何会导致此类注释的内容。

1 个答案:

答案 0 :(得分:2)

以下是使用annotation plugin和画布上自定义绘图可以执行的操作的示例:

var data_set = [{x: 1, y: 12}, {x: 2, y: 3}, {x: 3, y: 2}, {x: 4, y: 1}, {x: 5, y: 8}, {x: 6, y: 8}, {x: 7, y: 2}, {x: 8, y: 2}, {x: 9, y: 3}, {x: 10, y: 5}, {x: 11, y: 11}, {x: 12, y: 1}];
var labels = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];

var lines = [], id = 0;
var linesOn = false;

var data = {
  labels: labels,
  datasets: [{
    label: "My First dataset",
    backgroundColor: "rgba(5,215,2,0.2)",
    borderColor: "rgba(5,215,2,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(5,215,2,0.4)",
    hoverBorderColor: "rgba(5,215,2,1)",
    data: data_set,
  }]
};
addLine(7);
var option = {
  legend: false,
  title: {
    display: true,
  },
  annotation: {
    drawTime: "afterDraw",
    annotations: lines
  },
  scales: {
    xAxes: [{
      id: 'x-axis',
      type: 'linear',
      position: 'bottom',
      ticks: {
        max: 12,
        min: 1,
        stepSize: 1,
        callback: function(value, index, values) {
          return data.labels[index];
        }
      }
    }],
    yAxes: [{
      id: 'y-axis',
      type: 'linear',
    }],
  },
  animation: {
    duration: 1,
    onComplete: function () {
      var ctx = this.chart.ctx;
      console.log("onComplete", this,Chart.defaults.global)
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);    
      ctx.textAlign = "center";
      ctx.textBaseline = "bottom";
      var line = this.chart.annotation.elements.line1,
      x = line._model.x1-15,
      y = line._model.y1+5;
      ctx.fillStyle = line.options.label.fontColor;
      ctx.fillText("Y",x,y);
		}
  }
};

var myLineChart = Chart.Line('myChart', {
  data: data,
  options: option
});

function addLine(value) {
  id++;
  var ln = {
    id: "line" + id,
    type: "line",
    mode: "horizontal",
    scaleID: "y-axis",
    value: value,
    borderWidth: 2,
    borderColor: "red",
    label: {
      enabled: false,
      fontColor: "red",
    }
  };
  lines.push(ln);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script>

<canvas id="myChart" width="400" height="400"></canvas>

在示例中,我禁用了注释标签,在yAxis上显示并添加了自定义标签(请参阅animation.onComplete()处理程序)。