使用GoogleCharts更改颜色BarChart ruby

时间:2014-01-09 15:26:50

标签: ruby google-visualization

我正在尝试使用GoogleChart从相同的选项生成饼图和条形图(如果需要,可以使用自定义) 在Pie上一切正常,但条形图不想采用颜色。所以我做了研究,我试图添加一些系列来强制它改变颜色。但是,到目前为止,仍然是蓝色的!

你有什么想法吗?

option = {
          width: 700,
          height: 200,
          colors: @colors,#basic array of colors
          # Don't display negative values
          min_value: 0,
          title: vote.question,
          backgroundColor: { fill:'transparent' },
          is3D: true,
          # Displays items even if the value is 0
          sliceVisibilityThreshold: 0,
          legend: {alignment: "center"},
          vAxis: {format:'#%'},
          series: [{colors: '#3366cc'}, {colors: '#dc3912'}, {colors: '#ff9900'}, {colors: '#dc3912'}],
          isStacked: true
      }

我试图添加一些'硬盘'系列但是......

2 个答案:

答案 0 :(得分:0)

BarCharts按系列颜色数据,听起来你有一个包含多个点的数据系列。如果要更改条形图的颜色,则需要在DataTable中添加“样式”角色列,并指定其中的颜色:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');
data.addColumn('number', 'Value');
data.addColumn({type: 'string', role: 'style'});
data.addRows([
    ['Foo', 5, 'color: #3366cc'],
    ['Bar', 4, 'color: #dc3912'],
    ['Baz', 7, 'color: #ff9900'],
    ['Cad', 3, 'color: #dc3912']
]);

答案 1 :(得分:0)

我的解决方案,使用@asgallant提示。在Ruby中。 @colors基本上是一组预定义的颜色。

  @colors = ['#3366cc','#dc3912',"#ff9900","#109618","#990099","#0099c6","#dd4477","#66aa00","#b82e2e","#316395","#994499","#22aa99","#aaaa11","#6633cc","#e67300","#8b0707","#651067","#329262","#5574a6","#3b3eac","#b77322","#16d620","#b91383","#f4359e","#9c5935","#a9c413","#2a778d","#668d1c","#bea413","#0c5922","#743411"]

  # Initialize the datatable that will contains our charts data.
  data_table = GoogleVisualr::DataTable.new
  data_titles = []
  data_votes = []

  # Headers
  data_table.new_column('string', t('choices'))
  data_table.new_column('number', t('shared.new_top_bar.votes'))
  data_table.new_column('string', 'color', nil, 'style');
  vote.vote_options.each do |vote_option|
    data_titles.push(escape_javascript(vote_option.title))
    data_votes.push(vote_option.votes)
  end

  data_titles.each_with_index do |elm, i|
    data_table.add_row([data_titles[i], data_votes[i], "color: "+@colors[i]])
  end

  # Configure the default options for the charts.
  option = {
      width: 700,
      height: 200,
      #colors: @colors,
      # Don't display negative values
      min_value: 0,
      title: vote.question,
      backgroundColor: { fill:'transparent' },
      is3D: true,
      # Displays items even if the value is 0
      sliceVisibilityThreshold: 0,
      legend: {alignment: 'center'}
  }

  if data_titles.size > 5
    # Customisation if too much data.
    option[:height] = data_titles.size * 50# Make it bigger if there is too much parts to draw.
  end

  @charts[vote] = GoogleVisualr::Interactive::PieChart.new(data_table, option)
  @charts2[vote] = GoogleVisualr::Interactive::BarChart.new(data_table, option)