【问题标题】:Set different color for each bars using ChartJS in Angular 4在 Angular 4 中使用 ChartJS 为每个条设置不同的颜色
【发布时间】:2017-07-12 10:57:00
【问题描述】:

我对 Angular 很陌生,我正在使用 ChartJS 在我的 Angular 4 应用程序中绘制条形图。我想要每个条的颜色不同。我确实喜欢他们在这里http://www.chartjs.org/docs/latest/ 所说的话,但它不是工作

这是我的 html 文件:

<div>
  <div style="display: block">
    <canvas class="dashboard-tile-chart" baseChart
            [datasets]="barChartData"
            [labels]="barChartLabels"
            [options]="barChartOptions"
            [legend]="barChartLegend"
            [chartType]="barChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)"></canvas>
  </div>
</div>

component.ts 文件

export class BarGraphComponent implements OnInit {

  public barChartOptions: any = {
    scaleShowVerticalLines: false,
    responsive: true,
    scales: {
      xAxes: [{
        stacked: false,
        gridLines: {
          display: false
        }
      }],
      yAxes: [{
        stacked: false
      }]
    }
  };
  public barChartLabels: string[] = ['', '', '', '', '', '', ''];
  public barChartType = 'bar';
  public barChartLegend = false;

  public barChartData: any[] = [
      {
        data: [100, 150, 150, 100, 200, 150, 100],
        label: '',
        backgroundColor: [
          '#5cb85c',
          '#65C6BB',
          '#1BBC9B',
          '#f0ad4e',
          '#5cb85c',
          '#5cb85c',
          '#f0ad4e'
        ]
      }];
}

数据正在显示,但没有为每个条设置不同的颜色。

stackoverflow 上的其他类似主题说这样做:

myObjBar.datasets[0].bars[0].fillColor = "green"; //bar 1
myObjBar.datasets[0].bars[1].fillColor = "orange"; //bar 2

但我没有条形图的对象。

编辑:

如何动态设置条形颜色?我试过了:

const colors = [];
this.vitalValues.forEach(value => {
  colors.push(value.color);
});

const barColors: Array<any> = [{
  backgroundColor: colors
}];

this.barChartColors = barColors;

但没有效果..

【问题讨论】:

    标签: angular chart.js


    【解决方案1】:

    尝试使用以下...

    在您的 HTML 中,添加 [colors] 指令 ...

    <div>
      <div style="display: block">
        <canvas class="dashboard-tile-chart" baseChart
                [datasets]="barChartData"
                [labels]="barChartLabels"
                [options]="barChartOptions"
                [colors]="barChartColors"
                [legend]="barChartLegend"
                [chartType]="barChartType"
                (chartHover)="chartHovered($event)"
                (chartClick)="chartClicked($event)"></canvas>
      </div>
    </div>
    

    然后,在您的 component.ts 中,添加 ...

    public barChartColors:Array<any> = [{
       backgroundColor: ['red', 'yellow', 'green', 'orange']
    }];
    

    不是“Angular 4”专业人士,但 AFAIK 这应该可以工作

    【讨论】:

    • 非常感谢。我已经被这个东西困了一个小时了。
    • 另外我如何动态设置颜色。请看我的编辑
    • 这是一个差异。问题兄弟(+与chartjs无关。典型的angular 4问题),我对Angular 4了解不多,所以我不能给你一个合适的解决方案。您应该为此提出一个新问题。
    猜你喜欢
    • 2015-08-09
    • 2014-10-25
    • 2018-07-30
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多