【问题标题】:Make x label horizontal in ChartJS在ChartJS中使x标签水平
【发布时间】:2015-03-17 21:16:00
【问题描述】:

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

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

【问题讨论】:

  • 这里的棘手之处在于,IMO,标签仍然需要清楚地链接到其中一个值,将其水平放置,它将跨越其中 3 个,这使得它混淆了它真正附加的标签到。对截断 y 的快速修复是快速重写模板以添加前导空格。 scaleLabel: " "

标签: javascript html5-canvas chart.js


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您使用的是 chart.js 2.x,只需在 ticks 选项中设置 ma​​xRotation: 0minRotation: 0。如果您希望它们垂直,请改为设置 ma​​xRotation: 90minRotation: 90。如果你想要所有的 x-labels,你可能需要设置 autoSkip: false。下面是一个例子。

    var myChart = new Chart(ctx, {
      type: 'bar',
      data: chartData,
      options: {
        scales: {
          xAxes: [{
            ticks: {
              autoSkip: false,
              maxRotation: 0,
              minRotation: 0
            }
          }]
        }
      }
    });
    

    0 度的例子

    90 度示例

    【讨论】:

    • 很好,它只能处理更多数据,但图表数据只有一个数据,它不会应用最小轮换。为什么 ?有什么想法请给我建议
    • 有什么办法可以让单词换行而不是重叠?
    • @jonjie 我也在寻找一种方法来让文字换行。在这方面有什么运气吗?
    【解决方案3】:

    scales > x > ticks中使用旋转

    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>

    【讨论】:

      猜你喜欢
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 2023-01-20
      相关资源
      最近更新 更多