Google Charts - Change individual bar color

后端 未结 9 1491
走了就别回头了
走了就别回头了 2020-12-10 01:36

With Google Charts bar graph, is it possible to to change the color of one bar. For example I\'d like to make the 2006 data red (other bars are blue).

 funct         


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 01:40

    Here's an example of the above tips

    google.charts.load('current', { packages: ['corechart', 'bar'] })
    google.charts.setOnLoadCallback(drawStacked)
    
    function mt_rand (min, max) {
      var argc = arguments.length
      if (argc === 0) {
        min = 0
        max = 2147483647
      } else if (argc === 1) {
        throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given')
      }
      return Math.floor(Math.random() * (max - min + 1)) + min
    }
    
    function dechex (d) {
      var hex = Number(d).toString(16)
      hex = '000000'.substr(0, 6 - hex.length) + hex
      return hex
    }
    
    function str_pad (str) {
      str += ''
      while (str.length < 3) {
        str = str + str
      }
      return str
    }
    
    function random_color_part () {
      // return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', 1);
      return mt_rand(0, 255)
    }
    
    function random_color () {
      return 'rgb(' + random_color_part() + ',' + random_color_part() + ',' + random_color_part() + ')'
    }
    
    let $color = random_color()
    // alert($color);
    
    function drawStacked () {
      // var data = new google.visualization.DataTable();
    
      var data = google.visualization.arrayToDataTable([
        ['Element', 'Density', { role: 'style' }],
        ['cor-glenio-aleatoria', 8.94, random_color()], // RGB value
        ['cor-arlei-aleatoria', 10.49, random_color()], // English color name
        ['outra cor', 19.30, random_color()],
    
        ['outra cor fixa', 21.45, 'color: #e5e4e2' ] // CSS-style declaration
      ])
    
      var options = {
        title: 'Motivation and Energy Level Throughout the Day',
        isStacked: true,
        hAxis: {
          title: 'Time of Day',
          format: 'h:mm a',
          viewWindow: {
            min: [7, 30, 0],
            max: [17, 30, 0]
          }
        },
        vAxis: {
          title: 'Rating (scale of 1-10)'
        }
      }
    
      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'))
      chart.draw(data, options)
    }
    
    https://jsfiddle.net/zeh3pn6d/2
    

提交回复
热议问题