【问题标题】:How to add additional label in the middle of each bar using ChartJS如何使用 ChartJS 在每个条的中间添加额外的标签
【发布时间】:2020-03-01 13:42:51
【问题描述】:

我正在尝试在图表中间添加百分比值。

目前,我有以下内容:

我想让我的图表像这样:

那么如何使用 chartJS 在条形中间添加这个百分比值或任何类型的文本?

提前致谢。

【问题讨论】:

    标签: javascript charts chart.js bar-chart


    【解决方案1】:

    你可以使用chartjs-plugin-datalabels如下:

    new Chart(document.getElementById("myChart"), {
      type: "bar",
      data: {
        labels: ['A', 'B', 'C'],
        datasets: [{
            label: "X",
            data: [15, 8, 12],
            backgroundColor: "red"
          },
          {
            label: "Y",
            data: [7, 6, 15],
            backgroundColor: "blue"
          },
          {
            label: "Z",
            data: [6, 12, 10],
            backgroundColor: "green"
          }
        ]
      },
      options: {
        plugins: {
          datalabels: {
            formatter: (value, context) => {
              let total = context.chart.data.datasets[context.dataIndex].data.reduce((a, b) => a + b, 0);
              return Math.round(1000 / total * value) / 10 + '%';
            },
            color: 'white'
          }
        },
        scales: {
          xAxes: [{
            stacked: true
          }],
          yAxes: [{
            stacked: true
          }]
        }
      }
    });
    canvas {
      max-width: 400px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    <canvas id="myChart" width="10" height="5"></canvas>

    【讨论】:

    • 如果我有data: [15, 8, 12, 39]之类的数据,则会显示错误
    • 请显示更多代码和详细的错误信息,否则几乎无法提供帮助。
    • 感谢您的 cmets。我以不同的方式修复它。
    猜你喜欢
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    相关资源
    最近更新 更多