javascript 在 ChartJS 中使 x 标签水平

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28031873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:18:41  来源:igfitidea点击:

Make x label horizontal in ChartJS

javascripthtml5-canvaschart.js

提问by Yujun Wu

enter image description here

在此处输入图片说明

Drawing a line chart with ChartJS 1.0.1 as above. As it shows, the label in the x-axis is not horizontal although there are enough space. How can I make it horizontal?

使用 ChartJS 1.0.1 绘制折线图,​​如上。如图所示,尽管有足够的空间,但 x 轴上的标签不是水平的。我怎样才能让它水平?

A side question, noticed the y label, there are 1-2px clipped. How to fix that?

一个小问题,注意到 y 标签,有 1-2px 被剪掉了。如何解决?

回答by tabetomo

If you are using chart.js 2.x, just set maxRotation: 0and minRotation: 0in ticks options. If you want them vertical, set maxRotation: 90and minRotation: 90instead. And if you want to all x-labels, you may want to set autoSkip: false. The following is an example.

如果您使用的是 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
        }
      }]
    }
  }
});

example of 0 degree enter image description here

0度的例子 在此处输入图片说明

example of 90 degree enter image description here

90度的例子 在此处输入图片说明

回答by vnbt

try fix the function calculateXLabelRotation in chart.js

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

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