Chartjs数据标签未显示条形图上的标签

rdlzhqv9  于 2023-03-02  发布在  Chart.js
关注(0)|答案(1)|浏览(287)

我有一个通过chartjs构建的垂直条形图。我使用的是datalabels插件,我希望数据可以绘制在每个条形图上,但它是不可见的

const data = [
    {
        "date": "2023-02-23",
        "subscribers": 1208123
    },
    {
        "date": "2023-02-22",
        "subscribers": 1045338
    },
    {
        "date": "2023-02-21",
        "subscribers": 1043130
    },
    {
        "date": "2023-02-20",
        "subscribers": 1248035
    },
    {
        "date": "2023-02-19",
        "subscribers": 1243734
    },
    {
        "date": "2023-02-18",
        "subscribers": 1240317
    },
    {
        "date": "2023-02-17",
        "subscribers": 1033439
    },
    {
        "date": "2023-02-16",
        "subscribers": 974864
    }
];
  const chart_label = "Number of subscribers";

 const chart_canvas = document
      .getElementById("number_of_messages_delivered")
      .getContext("2d");
    Chart.defaults.set("plugins.datalabels", {
      color: "#FE777B",
    });
    push_messages_chart = new Chart(chart_canvas, {
      type: "bar",
      options: {
        animation: true,
        plugins: {
          // Change options for ALL labels of THIS CHART
          datalabels: {
            color: "#FFCE56",
            display: true, // Set to true to display the labels
          },
        },
      },
      data: {
        labels: data.map((row) => row.date),
        datasets: [
          {
            label: chart_label,
            data: data.map((row) => row.subscribers),
          },
        ],
      },
    });
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.2.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="number_of_messages_delivered"></canvas>

从上周开始我尝试了不同的迭代,但是没有任何效果。这只是我所尝试的一个随机样本

zzzyeukh

zzzyeukh1#

您忘记初始化插件!
添加以下内容:

Chart.register(ChartDataLabels);

一些附加信息/改进

  • datalabelscolor应该在labels.value对象里面。我已经移动了它,所以标签是正确的颜色(#FFCE56
  • dataset上的color应为backgroundColor,也进行了更改
  • 我已经在标签上实现了一个formatter,使用this question来说明如何应用千位分隔符,只是为了使它更具可读性(再次)。
formatter: n => numberWithCommas(n),
更新的代码段

一个二个一个一个

相关问题