最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to center the labels of a horizontal stacked bar chart in Chart.js? - Stack Overflow

programmeradmin3浏览0评论

I have created an horizontal stacked bar chart using Chart.js and Chartjs-plugin-datalabel. Here are the options I defined for the chart :

{
    indexAxis: "y",
    animation: false,
    aspectRatio: 0.2,
    maintainAspectRatio: false,
    scales: {
        x: {
            axis: "x",
        },
        y: {
            axis: "y",
        }
    },
    x: {
        beginAtZero: true,
        stacked: true
    },
    y: {
        beginAtZero: true,
        stacked: true
    },
    cutout: "50%",
    plugins: {
        title: {
            color: "gray",
            font: {
                weight: "bold",
                size: 12
            }
        },
        legend: {
            display: false,
            position: "top"
        },
        datalabels: {
            color: "white",
            align: "center",
            anchor: "center",
            textAlign: "center",
            formatter: (val: number, ctx: Context): string => {
              if (val) {
                const label = ctx.chart.data.labels[ctx.datasetIndex] as string;
                const value = ctx.chart.data.datasets[ctx.datasetIndex].data[0];
                return `${label} (${value})`;
              }
              return '';
            },
        },
        tooltip: {
            enabled: true,
            callbacks: {
              title: (): string => '',
              label: (tooltipItem: any): string => {
                const { chart } = tooltipItem;
                const label = chart.data.labels[tooltipItem.datasetIndex];
                const value: number = chart.data.datasets[tooltipItem.datasetIndex].data[0];
                return `${label}: ${value}`;
              },
            },
        },
    },
}

Then I use theses options in the html template like this :

<p-chart type="bar" [data]="data" [plugins]="barChartPlugins"
  [options]="options" width="280px" height="80px" />

(for those who wonder, I use Angular and Primeng)

I put everything to 'center' in the datalabels property. Here is the result :

I have tried to change the values of these properties, play with the offset, add padding top, but this does not enable me to move the labels in the center of the chart in a vertical axis (at the same level as the (23) on the right). They are always on the top and I cannot figure why.

How can I center them ?

PS : the result is not so bad here. It depends on the size of the chart, sometimes it is too small. Then the labels are too high and we cannot see the top of it. This is why I would like to center them.

发布评论

评论列表(0)

  1. 暂无评论