ChartJS,让条形图显示正确的百分比?

ChartJS, make the bars show correct percentage?

我有以下图表显示了一些数据及其百分比,百分比部分参考

它只对每个人左边的第一个条正确工作,其他条没有显示正确的百分比,我该如何解决这个问题?

它使用数据标签插件并在格式化程序中进行设置。我知道它发生在 const otherDatasetIndex 和 const total 中,但很难将代码修改为我需要的内容。

ChartJs 的新手。感谢任何帮助。

const trend_options = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    datalabels: {
      formatter: function(value, ctx) {
const otherDatasetIndex = ctx.datasetIndex % 2 === 0 ? ctx.datasetIndex + 1 : ctx.datasetIndex - 1;
        const total = ctx.chart.data.datasets[otherDatasetIndex].data[ctx.dataIndex] + value;
        return `${(value / total * 100).toFixed()}%`;
      },

      font: {
        weight: "bold"
      },
      color: "#fff",
      display: function(context) {
        let index = context.dataIndex;
        let value = context.dataset.data[index];
        return value > 0; // display labels with a value greater than 0
      }
    },
  },
  scales: {
    x: {
      stacked: true
    },
    y: {
      stacked: true,
      suggestedMax: 15,
      ticks: {
        beginAtZero: true,
        stepSize: 5,
      }
    }
  },
};


const app_data_trend = [{
    label: 'App Month 1 TW',
    data: [3, 4, 5, 6, 4, 4, 4],
    backgroundColor: '#007bff',
    stack: 'Stack 0',
  },
  {
    label: 'App Month 1 jira',
    data: [3, 4, 5, 4, 3, 2, 3],
    backgroundColor: '#6DB526',
    stack: 'Stack 0',
  },
  {
    label: 'App Month 2 TW',
    data: [4, 4, 4, 3, 2, 5, 4],
    backgroundColor: 'pink',
    stack: 'Stack 1',
  },
  {
    label: 'App Month 2 jira',
    data: [4, 2, 5, 2, 3, 3, 4],
    backgroundColor: 'red',
    stack: 'Stack 1',
  },
  {
    label: 'App Month 3 TW',
    data: [2, 4, 5, 2, 4, 5, 3],
    backgroundColor: 'grey',
    stack: 'Stack 2',
  },
  {
    label: 'App Month 3 jira',
    data: [1, 1, 2, 4, 4, 3, 5],
    backgroundColor: 'yellow',
    stack: 'Stack 2',
  },

]

const ctx8 = document.getElementById("tsa-applications-trending");
const chart8 = new Chart(ctx8, {
  plugins: [ChartDataLabels],
  type: 'bar',
  data: {
    labels: ['person1', 'person2', 'person3', 'person4'],
    datasets: app_data_trend
  },
  options: trend_options,
});
.chart-container{
position: relative; height:80vh; width:80vw
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
<div class="chart-container">
  <canvas id="tsa-applications-trending"></canvas>
</div>

我认为您的问题与以下行有关:

const otherDatasetIndex = ctx.datasetIndex === 0 ? 1 : 0;

这将始终使用第一个数据集进行比较。总共有 6 个数据集,您想要比较两个数据集。下面的代码应该可以解决这个问题。

const otherDatasetIndex = ctx.datasetIndex % 2 === 0 ? ctx.datasetIndex + 1 : ctx.datasetIndex - 1;

这将比较数组中所有偶数数据集和它后面的奇数数据集以及所有奇数数据集和它前面的偶数数据集。