【问题标题】:Chart.js bar chart with time on X axis and category on Y axis is not rendered未呈现 X 轴上时间和 Y 轴上类别的 Chart.js 条形图
【发布时间】:2020-02-23 18:44:56
【问题描述】:

使用最新的 chart.js,我无法创建 X 轴为时间、Y 轴为类别的条形图。

<div style="display: block;">
  <canvas baseChart 
    [datasets]="barChartData"
    [options]="barChartOptions"
    [plugins]="barChartPlugins"
    [legend]="barChartLegend"
    [chartType]="barChartType">
  </canvas>
</div>

打字稿:

import { Component, OnInit } from '@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public barChartOptions: ChartOptions = {
    responsive: true,
    scales: {
      xAxes: [{
        type: 'time'
      }],
      yAxes: [{
        type: 'category',
        labels: ['Yes', 'No']
      }]
    }
  };

  public barChartType: ChartType = 'line';
  public barChartLegend = false;

  public barChartData: ChartDataSets[] = [
    { data: [
      {x: new Date('2020-02-20'), y: 'Yes'}, 
      {x: new Date('2020-02-22'), y: 'No'},
      {x: new Date('2020-02-23'), y: 'Yes'},
      {x: new Date('2020-02-24'), y: 'No'}
      ] 
    }
  ];

  constructor() { }

  ngOnInit() {
  }
}

这提供了不错的折线图,但是一旦我将类型更改为“条形图”,就不会呈现任何内容。

线条完美:

栏是空的:

https://stackblitz.com/edit/ng2-charts-bar-template-aolnys

【问题讨论】:

  • 问题是数据,你想在条形图中如何表示?
  • @Sajeetharan - 我想看 4 个酒吧 :-) 想象一下门的状态 - 门在 20 日、22 日、23 日、24 日打开,但在 21 日关闭。或者空气质量——好、一般、差。我还尝试将数据结构从 [x, y] 更改为单独的标签和数据,但没有运气。
  • 条形图上不能有 x 和两个不同的 y 值,但可以有数字
  • @Sajeetharan 数据中的一个 X 值总是有一个 Y 值。如果我将数字放在 Y 轴上,它可以工作,但我想查看特定类别的值。就像星期天空气质量很好,星期一很差,星期二没有测量……这样的图表有什么问题?

标签: angular charts chart.js


【解决方案1】:

您可以将yAxis 值定义为数字。在我的代码中“是”= 2 和“否”= 1。

data: [2, 1, 2, 1]

然后使用yAxist.ticks.callback 返回有意义的刻度标签

yAxes: [{
  ticks: {
    beginAtZero: true,
    stepSize: 1,
    callback: value => {
      if (value == 0) {
        return '';
      }
      return value == 1 ? 'No' : 'Yes';
    }
  }
}]

请看下面StackBlitz

【讨论】:

  • 好招!谢谢!我仍然很好奇为什么类别类型不起作用...
猜你喜欢
  • 1970-01-01
  • 2022-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多