Tick Configuration

This sample shows how to use different tick features to control how tick labels are shown on the X axis. These features include:

  • Multi-line labels
  • Filtering labels
  • Changing the tick color
  • Changing the tick alignment for the X axis

Tick Configuration - 图1

config setup actions

  1. const config = {
  2. type: 'line',
  3. data: data,
  4. options: {
  5. responsive: true,
  6. plugins: {
  7. title: {
  8. display: true,
  9. text: 'Chart with Tick Configuration'
  10. }
  11. },
  12. scales: {
  13. x: {
  14. ticks: {
  15. // For a category axis, the val is the index so the lookup via getLabelForValue is needed
  16. callback: function(val, index) {
  17. // Hide the label of every 2nd dataset
  18. return index % 2 === 0 ? this.getLabelForValue(val) : '';
  19. },
  20. color: 'red',
  21. }
  22. }
  23. }
  24. },
  25. };
  1. const DATA_COUNT = 12;
  2. const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100};
  3. const data = {
  4. labels: [['June', '2015'], 'July', 'August', 'September', 'October', 'November', 'December', ['January', '2016'], 'February', 'March', 'April', 'May'],
  5. datasets: [
  6. {
  7. label: 'Dataset 1',
  8. data: Utils.numbers(NUMBER_CFG),
  9. fill: false,
  10. borderColor: Utils.CHART_COLORS.red,
  11. backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5),
  12. },
  13. {
  14. label: 'Dataset 2',
  15. data: Utils.numbers(NUMBER_CFG),
  16. fill: false,
  17. borderColor: Utils.CHART_COLORS.blue,
  18. backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5),
  19. }
  20. ]
  21. };
  1. const actions = [
  2. {
  3. name: 'Alignment: start',
  4. handler(chart) {
  5. chart.options.scales.x.ticks.align = 'start';
  6. chart.update();
  7. }
  8. },
  9. {
  10. name: 'Alignment: center (default)',
  11. handler(chart) {
  12. chart.options.scales.x.ticks.align = 'center';
  13. chart.update();
  14. }
  15. },
  16. {
  17. name: 'Alignment: end',
  18. handler(chart) {
  19. chart.options.scales.x.ticks.align = 'end';
  20. chart.update();
  21. }
  22. },
  23. ];