【问题标题】:Changing Google Stacked Bar Chart colors (Material Bar Chart)更改 Google 堆积条形图颜色(材质条形图)
【发布时间】:2015-07-08 05:52:09
【问题描述】:
var data = google.visualization.arrayToDataTable(stats_data);

var options = {
    width: 1400,
    height: 400,
    legend: { position: 'top', maxLines: 3 },
    bar: { groupWidth: '75%' },
    isStacked: true,
    bars: 'vertical',
    colors:['#999','#346ac9', '#279423', '#fc9826'],
};

var chart = new google.charts.Bar(document.getElementById('chart-recent'));
chart.draw(data, google.charts.Bar.convertOptions(options));

我有一个堆积条形图,我希望每种颜色都不同(灰色、蓝色、绿色、橙色)。但是,部分的颜色只是在多个亮度中取第一种颜色(灰色)。

我也在我的options 中尝试过这个:

series: [
    {color: '#999'},
    {color: '#346ac9'},
    {color: '#279423'},
    {color: '#fc9826'}
]

如何让每个系列都有不同的颜色?

【问题讨论】:

  • colors 选项似乎对我有用here

标签: javascript charts material-design


【解决方案1】:

我能够让颜色正常工作here

生成图表时,我必须使用:new google.visualization.ColumnChart(...) 而不是 new google.charts.Bar(...),否则无法正确堆叠。


您可能还需要确保您使用的是最新版本的 Google 图表。在上面的小提琴中,我使用了来自developer docs 的样本,它们使用:https://www.google.com/jsapi 来自动加载所有东西。

【讨论】:

  • 请注意,google.visualization.ColumnChart() 适用于旧的 Classic 图表,而不是新的 Material 图表。在 Google 弄清楚材料图表之前,人类将在火星上拥有一个永久殖民地。
【解决方案2】:

在提出原始问题时,材料条形图可能还不支持堆叠条形图的自定义颜色。

今天,series 配置选项作为 颜色对象数组 似乎工作正常。请参阅下面示例中的 colors 变量。

示例代码:

const data = [
   ['Sector',        'High', 'Medium', 'Low' ],
   ['Agriculture',   18,  9, 29],
   ['Education',      2, 14, 10],
   ['Healthcare',     4,  6, 41],
   ['Manufacturing', 36, 10,  3]
   ];
const colors = [
   { color: 'indianred' },  //high
   { color: 'khaki' },      //medium
   { color: 'seagreen' },   //low
   ];

const drawChart = () => {
   const options = {
      chart:   { title: 'Risk by sector' },
      legend:  { position: 'top' },  //not yet supported
      bars:    'horizontal',
      stacked: true,
      series:  colors
      };
   const chartData = google.visualization.arrayToDataTable(data);
   const elem = $('figure#health-chart')[0];
   const chart = new google.charts.Bar(elem);
   chart.draw(chartData, options);
   };

google.charts.load('current', { packages: ['bar'] });
google.charts.setOnLoadCallback(drawChart);

结果图表:

修改代码:
https://jsfiddle.net/p8bnfe2h

配置选项

series
一组对象,每个对象描述图表中相应系列的格式。要为系列使用默认值,请指定一个空对象 {}。如果未指定系列或值,则将使用全局值。

文档:
https://developers.google.com/chart/interactive/docs/gallery/barchart#configuration-options

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2020-11-03
    • 2020-05-21
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多