【问题标题】:Chart.js V3 Fill Below 0Chart.js V3 填充低于 0
【发布时间】:2021-07-01 23:32:51
【问题描述】:

我正在寻找一种方法来将图表上低于 0 的所有内容填充为漂亮的红色阴影。在搜索了 SO 和文档之后,我还没有找到一种方法来做到这一点。我尝试创建一个填充有decimal.MinValue 的数据集,并将低于 0 的所有内容设置为已填充,但无论数据集是否设置为隐藏,它都会将整个图表向下移动到最小值。任何建议将不胜感激。谢谢

【问题讨论】:

标签: chart.js


【解决方案1】:

您可以为此使用自定义内联插件:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [100, 19, 3, 5, -10, 3],
        borderColor: 'red',
        backgroundColor: 'red'
      },
      {
        label: '# of Votes2',
        data: [20, 10, 4, 3, -30, 32],
        borderColor: 'blue',
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      backgrounds: {
        hbars: [{
          from: 0,
          to: 'MIN',
          color: "rgb(230, 195, 195)"
        }]
      }
    }
  },
  plugins: [{
    id: 'backgrounds',
    beforeDraw: (chart, args, options) => {
      const {
        canvas,
        ctx,
        chartArea,
        scales: {
          y
        }
      } = chart;
      let from = 0;
      let to = 0;

      options.hbars.forEach((hBar) => {
        from = hBar.from;
        to = hBar.to;

        from = from === 'MIN' ? y.min : from;
        from = from === 'MAX' ? y.max : from;

        to = to === 'MIN' ? y.min : to;
        to = to === 'MAX' ? y.max : to;

        ctx.save(canvas.width, canvas.height);
        ctx.fillStyle = hBar.color;
        ctx.fillRect(chartArea.left, y.getPixelForValue(from), chartArea.right - chartArea.left, y.getPixelForValue(to) - y.getPixelForValue(hBar.from));
        ctx.restore();
      })
    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
</body>

【讨论】:

  • @LeeLanalee 太棒了!有没有办法让它不填在标签后面?非常感谢您的帮助!
  • 标签后面没有填满?它停在 y 刻度的底部
  • ibb.co/hdDmL1c 另外,我还在搜索自己,但你知道我在更改数据集时会使用哪个事件来更新它吗?
  • 实际上,我认为过去的标签阴影在我身上。在我的页面加载之前,我有一个点在 -1000 的数据集。当我的页面完成加载并且图表数据集填充了实际数据时,背景没有更新,因此看起来好像阴影越过了标签。一旦我弄清楚数据集更新后的更新阴影应该可以解决问题。
  • 我想我可能知道问题出在哪里,正在尝试解决它
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多