首页 > 解决方案 > 在chartJs中添加多行作为Y轴标题

问题描述

我试图在由 chartJs 创建的图表中为 Y 轴添加多行标题。我可以发现图表的整个标题可以使用字符串数组来执行此操作,但没有找到任何选项可以对任何轴执行相同操作。

我目前使用以下选项播种标题:

 scales: {
  yAxes: [
    {
      ticks: {
        beginAtZero: true,
      },
      scaleLabel: {
        display: true,
        labelString: "Deviation from average \n Total" //Multi line label
      },
    }
  ],

StackBlitz复制相同。

电流输出:

在此处输入图像描述

预期输出:

在此处输入图像描述

标签: javascriptangularchart.jsng2-charts

解决方案


您必须更新到 lib 版本 3 才能使用此功能,在这里您可以将比例标题的文本也指定为数组以使其多行。

angular wrapper stable build 仅支持 v2 atm,它们具有可用于 v3 的 beta 构建,因此您需要安装带有next标签的 wrapper 以安装 beta 版本或在 package.json 中指定所需的版本

简单的例子:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      y: {
        title: {
          display: true,
          text: ['first line', 'second line'] // array so it becomes multi lined
        },
        ticks: {
          reverse: false
        }
      }
    }
  }
}

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.2.0/chart.js" integrity="sha512-opXrgVcTHsEVdBUZqTPlW9S8+99hNbaHmXtAdXXc61OUU6gOII5ku/PzZFqexHXc3hnK8IrJKHo+T7O4GRIJcw==" crossorigin="anonymous"></script>
</body>


推荐阅读