在ChartJS中使x轴标签水平显示

16

enter image description here

使用ChartJS 1.0.1绘制线图如上所示。如图所示,尽管有足够的空间,但x轴标签不是水平的。我该如何使其水平呢?

附带一个问题,注意到y轴标签被剪裁了1-2像素。如何解决这个问题呢?


2
这里的棘手之处在于,我认为标签仍然需要与其中一个值清晰地关联起来,如果将其水平放置,则会跨越其中的3个值,使得它真正附加到哪个标签变得混淆。修复被截断的y的快速方法是重写模板以添加前导空格。scaleLabel:“<%= value%>” - Quince
4个回答

46
如果您正在使用 chart.js 2.x 版本,则只需在刻度选项中设置 maxRotation: 0minRotation: 0,如果你想要它们垂直显示,则设置为 maxRotation: 90minRotation: 90。如果您想显示所有的 x 标签,则可以设置 autoSkip: false。以下是一个示例。
var myChart = new Chart(ctx, {
  type: 'bar',
  data: chartData,
  options: {
    scales: {
      xAxes: [{
        ticks: {
          autoSkip: false,
          maxRotation: 0,
          minRotation: 0
        }
      }]
    }
  }
});

0度的示例 这里输入图片描述

90度的示例 这里输入图片描述


太好了,它正在工作,只是有更多的数据,但图表数据只有一个数据,它不会应用最小旋转。为什么?有什么想法请建议我。 - VjyV
2
有没有办法让单词换行而不是重叠在一起? - Blues Clues
@jonjie 我正在寻找一种让文字也能自动换行的方法。在这方面有什么进展吗? - M. Straw

2

scales > x > ticks 中使用旋转(Rotation)

scales: {
   x: {
    ticks: {
      autoSkip: false,
      maxRotation: 90,
      minRotation: 90
    }
   }
}

let chart = new Chart('myChart', {

type: 'line',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            x: {
                ticks: {
                  autoSkip: false,
                  maxRotation: 90,
                  minRotation: 90
                }
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.2/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>


1

尝试修复 chart.js 中的 calculateXLabelRotation 函数。

calculateXLabelRotation : function(){
    ...
        //↓↓↓
        this.xLabelRotation = 0;
        //↑↑↑
        if (this.xLabelRotation > 0){
            this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
        }
    ...
},

0

这是我的选项配置

const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      tooltip: {
        enabled: true
      },
    },
    scales: {
        xAxis: {
            ticks: {
                maxTicksLimit: 7,
                minRotation: 0,
                maxRotation: 0
            }
        }
    }
  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接