如何在同一侧 chartjs React 对齐标签

How to align labels at same side chartjs React

你好,我正在使用图表 js 渲染这些图表,但我无法按照相同的顺序对齐这些图表,我的配置文件和选项文件如下所示 谁能帮我解决这个问题。我尝试了以下选项和数据

const options = {
    indexAxis: "y",
    maintainAspectRatio: false,
    aspectRatio: 0.8,
    barThickness: 20,
    responsive: true,
    layout: {
        padding: {
            left: 1
        }
    },
    plugins: {
        legend: {
            display: false
        }
    },
    scales: {
        x: {
            ticks: {
                color: "#495057"
            },
            grid: {
                color: "#ebedef"
            }
        },
        y: {
            ticks: {
                color: "#495057",
                crossAlign: "near"
            },
            grid: {
                color: "#ebedef"
            },
            gridLines: {
                offsetGridLines: true,
                display: true
            }
        }
    }
};


const data = {
    labels: ["red"],
    datasets: [{
            backgroundColor: "#42A5F5",
            data: [65],
            borderWidth: 2,
            borderRadius: 75,
            borderSkipped: false
        },
        {
            backgroundColor: "#FFA726",
            data: [28],
            borderWidth: 2,
            borderRadius: 50,
            borderSkipped: false
        }
    ]
};

如何将一个标签对齐到其他标签下方

据我所知 chart.js 没有提供为标签设置最小距离的选项,实现此目的的解决方法是在标签较短的图表标签中添加空格最长的一个,所以你会得到这样的东西:

var options = {
  type: 'bar',
  data: {
    labels: ["                Red"],
    datasets: [{
      label: '# of Votes',
      data: [12],
      backgroundColor: 'pink'
    }]
  },
  options: {
    indexAxis: 'y'
  }
}

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.5.0/chart.js"></script>
</body>

var options = {
  type: 'bar',
  data: {
    labels: ["                Red"],
    datasets: [{
      label: '# of Votes',
      data: [12],
      backgroundColor: 'pink'
    }]
  },
  options: {
    indexAxis: 'y'
  }
}
var options2 = {
  type: 'bar',
  data: {
    labels: ["   Yellowwwww"],
    datasets: [{
      label: '# of Votes',
      data: [12],
      backgroundColor: 'pink'
    }]
  },
  options: {
    indexAxis: 'y'
  }
}

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