ChartJS刻度线中的不同样式 [英] Different styles in ticks on ChartJS

查看:40
本文介绍了ChartJS刻度线中的不同样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能将xAxes的样式分隔在刻度线中或通过其他功能绘制near.Callback-只需使用值即可操作.

Is it possible to separate styles in ticks for xAxes or draw by some other function near.Callback - just operate with values.

例如:

推荐答案

您可以使用

You can make use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In below code snippet, I use the afterDraw hook to draw text of different styles underneath each bars.

请注意,在编写自己的标签标签时无需计算文本大小.您只需在第一个文本部分添加一个空格,然后使用 ctx.textAlign 'right',然后使用 ctx.textAlign 'left'绘制第二个文本部分.

Note that no computation of text size is needed when composing your own labels labels. You can simply add a space to the first text section and use ctx.textAlign 'right', then use ctx.textAlign 'left' for drawing the second text section.

绘制自己的刻度标签时,需要指示Chart.js不要显示默认标签.这可以通过图表 options 中的以下定义来完成.

scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }], 

您还需要在图表底部定义一些填充,否则您将看不到自定义刻度标签.

You also need to define some padding for the bottom of the chart, otherwise you won't see your custom tick labels.

layout: {
  padding: {
    bottom: 20
  }
},

new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      ctx.save();
      chart.data.labels.forEach((l, i) => {
        var value = chart.data.datasets[0].data[i];
        var x = xAxis.getPixelForValue(l);
        ctx.textAlign = 'right';
        ctx.font = '12px Arial';
        ctx.fillText(l + ' ', x, yAxis.bottom + 18);
        ctx.textAlign = 'left';
        ctx.font = 'bold 14px Arial';
        ctx.fillStyle = 'blue';
        ctx.fillText(value, x, yAxis.bottom + 17);
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ['Error', 'Warn', 'Info'],
    datasets: [{
      label: 'My First Dataset',
      data: [30, 59, 80],
      fill: false,
      backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 205, 86, 0.2)'],
      borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)'],
      borderWidth: 1
    }]
  },
  options: {
    layout: {
      padding: {
        bottom: 20
      }
    },
    scales: {
      xAxes: [{
        ticks: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

canvas {
  max-width: 400px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" width="10" height="5"></canvas>

这篇关于ChartJS刻度线中的不同样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆