如何使用Chart.js在标签中放置新行?

时间:2019-05-23 21:49:52

标签: javascript chart.js chart.js2

我有一个使用Chart.js的带有标签的数据集。我想将标签分成两行,并使用换行符。

我尝试过PackageManager p = getPackageManager(); ComponentName componentName = new ComponentName(this, com.apps.MainActivity.class); p.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); ActivityNotFoundException,但都没有用。

<br />

第一个标签应显示为...

  

(A)
醒来

但它最终看起来像...

  

(A)\n醒来

     

(A)醒来

1 个答案:

答案 0 :(得分:3)

看这张示例图https://www.chartjs.org/samples/latest/scales/multiline-labels.html,我发现多行标签是可行的。

我查看了上面示例的源代码,对于多行标签,它们在数组中具有每条多行,而数组中的每个元素都在其自己的行中呈现。

例如:

labels: [['(A)', 'Waking'], '(B)', '(C)', '(D)'],

请参见下面的演示:

var randomScalingFactor = function() {
  return Math.round(Math.random() * 100);
};

window.chartColors = {
	red: 'rgb(255, 99, 132)',
	orange: 'rgb(255, 159, 64)',
	yellow: 'rgb(255, 205, 86)',
	green: 'rgb(75, 192, 192)',
	blue: 'rgb(54, 162, 235)',
	purple: 'rgb(153, 102, 255)',
	grey: 'rgb(201, 203, 207)'
};

var config = {
  type: 'line',
  data: {
    labels: [
      ['(A)', 'Walking'], '(B)', '(C)', '(D)'],
    datasets: [{
      label: 'My First dataset',
      fill: false,
      backgroundColor: window.chartColors.red,
      borderColor: window.chartColors.red,
      data: [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor()        
      ]
    }, {
      label: 'My Second dataset',
      fill: false,
      backgroundColor: window.chartColors.blue,
      borderColor: window.chartColors.blue,
      data: [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor()
      ],
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart with Multiline Labels'
    },
  }
};

window.onload = function() {
  var ctx = document.getElementById('canvas').getContext('2d');
  window.myLine = new Chart(ctx, config);
};
<script src="https://www.chartjs.org/dist/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.cloudflare.com/cdn-cgi/scripts/a2bd7673/cloudflare-static/rocket-loader.min.js" data-cf-settings="100752039a7e60f6a2c8f47d-|49"></script>

<div style="width:90%;">
  <canvas id="canvas"></canvas>
</div>