ChartJS X轴标签全部显示

mwg9r5ms  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(182)
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
    <div style="width:50%">
    <canvas id="chart2" style="width:100%"></canvas>
    </div>
    <script>
    var yLabels = {
        1 : 'New',
      2 : 'Learning Phase',
      3 : 'Good',
      4 : 'Strong',
      5 : 'Master'
    }

    Chart.register(ChartDataLabels);
    new Chart('chart2', {
      type: 'bar',
      data: {
        labels: ['Tommy','Fred'],
        datasets: [{
          data: [3,1],
        }]
      },
      options: {

        indexAxis: 'y',
        layout: {
          padding: {
            right: 60
          }
        },
        plugins: {
          title: {
            display: true,
            text: "Skill Chart"
          },
          legend: {
            display: false,
          },
          datalabels: {
            color: 'blue',
                formatter: (value) => {
                if (value == 1) {
                    value = 'New';
                    return value;
                }
                if (value == 2) {
                    value = 'Learning Phase';
                    return value;
                }

                if (value == 3) {
                    value = 'Good';
                    return value;
                }
                if (value == 4) {
                    value = 'Strong';
                    return value;
                }
                if (value == 5) {
                    value = 'Master';
                    return value;
                }
                },
            anchor: 'end',
            align: 'right',
            labels: {
              title: {
                font: {
                  weight: 'bold'
                }
              }
            }
          }
        },
        scales: {
          y: {
            grid: {
              display: false
            },
                  ticks: {
            },
          },
          x: {
          ticks:{
            callback: function(value, index, values) {
                  return yLabels[value];
              },
          precision: 1,
          },
            grid: {
              display: false,
            }
          }
        }
      }
    });
    </script>

上面是一个可以工作的代码,但是我现在面临的是如何在x轴上显示"变量ylabels中的所有标签“?我试过autoSkip:false。它不起作用。
我想要的是,它显示了所有的标签从(新到主),尽管数据只有3和1。如果我改变了标签为“5”一切工作完美。
https://codepen.io/kennyl80841728/pen/jOxzLjy

slmsl1lt

slmsl1lt1#

您需要定义options.scales.x.max,如下所示:

options: {
  scales: {
    x: {
      max: 5,
      ...

有关详细信息,请参阅Chart.js文档中的最小最大配置

相关问题