【问题标题】:How can I change background color of a specific area in my chart's grid using Chart.js and Annotation?如何使用 Chart.js 和 Annotation 更改图表网格中特定区域的背景颜色?
【发布时间】:2024-01-07 15:59:01
【问题描述】:

我在尝试更改两个 yAxis 刻度之间特定图表区域的背景颜色时遇到了一些麻烦。这是我目前所拥有的:

这就是我想要的:

我看过一些类似的帖子,人们建议使用 Annotation 来做到这一点。我尝试在我的图表上使用它,但它不起作用。这是我第一次使用 chart.js 构建图表,所以我还在学习。这是我的代码:

var profileChart = new Chart(ctx1, {
type: "line",
data: {
    labels: ["", "D", "I", "S", "C", ""],
    datasets:[{
        data: [],
        borderWidth: 1,
        pointBackgroundColor: "black",
        backgroundColor: "black",
        borderColor: "black",
        fill: false,
        lineTension: 0, 
        yAxisID: 'first-y-axis'
    },
    {
        yAxisID: 'third-y-axis'
    }],
},
options: {
    title: {
        display: true,
        text: 'Gráfico do Perfil DISC',
        fontSize: 20,
    },
    scales: {
        yAxes: [{
            id: 'first-y-axis',
            type: 'linear',
            gridLines: {
                drawOnChartArea: false
            },
            scaleLabel: {
                display: true,
                padding: '15px',
                labelString: 'Intensity'
              },
            ticks: {
                max: 28,
                min: 1,
                stepSize: 1
            }
        },
        {
            id: 'second-y-axis',
            type: 'linear',
            position: 'left',
            gridLines: {
                drawOnChartArea: true
            },
            ticks: {
                display: false,
                min: 1,
                max: 8,
                stepSize: 1
            }
        },
        {
            id: 'third-y-axis',
            position: 'right',
            type: 'linear',
            gridLines: {
                drawOnChartArea: false
            },
            scaleLabel: {
                display: true,
                padding: '10px',
                labelString: 'Segment'
              },
            ticks: {
                max: 7.5,
                min: 0.5,
                stepSize: 1
            },
            afterTickToLabelConversion: function(scaleInstance) {
                scaleInstance.ticks[0] = null;
                scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
                scaleInstance.ticksAsNumbers[0] = null;
                scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
              },
        }] 
    },
    legend: {
        display: false
    },
    tooltips: {
        callbacks: {
           label: function(tooltipItem) {
                  return tooltipItem.yLabel;
           }
        }
    }
},
annotation: {
    drawTime: "afterDraw",
    annotations: [{
        id: 'box1',
      type: 'box',
      yScaleID: 'second-y-axis',
      yMin: 12.5,
      yMax: 16.5,
      backgroundColor: 'grey',
    }]
  }
});

【问题讨论】:

    标签: javascript chart.js linechart


    【解决方案1】:

    您可以使用Plugin Core API 直接在画布上绘制矩形。 API 提供了一系列可用于执行自定义代码的钩子。

    在您修改后的代码中,我使用beforeDraw 钩子通过CanvasRenderingContext2D.fillRect() 绘制矩形。

    var profileChart = new Chart('canvas', {
      type: "line",
      plugins: [{
        beforeDraw: chart => {
          var ctx = chart.chart.ctx;
          var xAxis = chart.scales['x-axis-0'];
          var yAxis = chart.scales['first-y-axis'];       
          ctx.save();            
          ctx.fillStyle  = 'lightgray';
          ctx.beginPath();    
          var yTop = yAxis.getPixelForValue(16.5);
          var yBottom = yAxis.getPixelForValue(12.5);
          ctx.fillRect(xAxis.left, yTop, xAxis.right - xAxis.left, yBottom - yTop);
          ctx.stroke();            
          ctx.restore();
        }
      }],
      data: {
        labels: ["", "D", "I", "S", "C", ""],
        datasets: [{
            data: [,25.5, 8, 7.5, 11],
            borderWidth: 1,
            pointBackgroundColor: "black",
            backgroundColor: "black",
            borderColor: "black",
            fill: false,
            lineTension: 0,
            yAxisID: 'first-y-axis'
          },
          {
            yAxisID: 'third-y-axis'
          }
        ],
      },
      options: {
        title: {
          display: true,
          text: 'Gráfico do Perfil DISC',
          fontSize: 20,
        },
        scales: {
          yAxes: [{
              id: 'first-y-axis',
              type: 'linear',
              gridLines: {
                drawOnChartArea: false
              },
              scaleLabel: {
                display: true,
                padding: '15px',
                labelString: 'Intensity'
              },
              ticks: {
                max: 28,
                min: 1,
                stepSize: 1
              }
            },
            {
              id: 'second-y-axis',
              type: 'linear',
              position: 'left',
              gridLines: {
                drawOnChartArea: true
              },
              ticks: {
                display: false,
                min: 1,
                max: 8,
                stepSize: 1
              }
            },
            {
              id: 'third-y-axis',
              position: 'right',
              type: 'linear',
              gridLines: {
                drawOnChartArea: false
              },
              scaleLabel: {
                display: true,
                padding: '10px',
                labelString: 'Segment'
              },
              ticks: {
                max: 7.5,
                min: 0.5,
                stepSize: 1
              },
              afterTickToLabelConversion: function(scaleInstance) {
                scaleInstance.ticks[0] = null;
                scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
                scaleInstance.ticksAsNumbers[0] = null;
                scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
              },
            }
          ]
        },
        legend: {
          display: false
        },
        tooltips: {
          callbacks: {
            label: function(tooltipItem) {
              return tooltipItem.yLabel;
            }
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
    <canvas id="canvas" height="200">

    【讨论】:

      最近更新 更多