Google 图表中的自定义图例多种颜色

Custom Legend multiple colors in Google Chart

我遇到无法将此图表的默认图例颜色自定义为多种颜色的问题,请帮助我。 这是image describe my problem , I am using stacked bar chart。这是我的代码:

//dump data arr
var data = google.visualization.arrayToDataTable([[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.581,"#b4ddfd",0.109,"#84bfef",0.21,"#559ad2",0.1,"#4277a1"],["nationality",0.481,"#ffddba",0.209,"#ffc384",0.25,"#ffac5b",0.06,"#fa993f"]],[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.1,"#b4ddfd",0.2,"#84bfef",0.3,"#559ad2",0.4,"#4277a1"],["nationality",0.4,"#ffddba",0.3,"#ffc384",0.2,"#ffac5b",0.1,"#fa993f"]],[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.5,"#b4ddfd",0.5,"#84bfef",0,"#559ad2",0,"#4277a1"],["nationality",0,"#ffddba",0,"#ffc384",0,"#ffac5b",1,"#fa993f"]],[["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],["A class",0.01,"#b4ddfd",0.02,"#84bfef",0.03,"#559ad2",0.94,"#4277a1"],["nationality",0.4,"#ffddba",0.3,"#ffc384",0.2,"#ffac5b",0.1,"#fa993f"]]]);
var options = {
        series: {
            0: {
                color: '#b4ddfd'
            },
            1: {
                color: '#84bfef'
            },
            2: {
                color: '#559ad2'
            },
            3: {
                color: '#4277a1'
            },
        },
        vAxis: {
            textStyle: {fontSize: 11},
            titleTextStyle: {italic: false},
        },
        chartArea: {
            width: '85%',
            height: areaHeight,
            top: 30,
            left: '13%'
        },
        bar: {groupWidth: '35%'},
        legend: {
            position: 'bottom',
            textStyle: {fontSize: 11},
        },
        isStacked: 'percent',
        hAxis: {
            ticks: [0, 1],
            textStyle: {fontSize: 13},
            minValue: 0,
            maxValue: 1,
        },
        callbackLegend: function(legend) {
            // my problem here
            // var legend_div = document.getElementById(graphId + '_legend');
            // legend_div.innerHTML = legend.innerHTML;
        },
        width: 920,
        height: areaHeight + 100
    };
var chart = new google.visualization.BarChart(document.getElementById('#chart_div'));
    chart.draw(data, options);

请帮帮我,我陷入僵局。

google 图表上的标准图例不会显示多种颜色。
事实上,当使用样式列角色时,
图例将与数据 table.

中样式列中使用的颜色不匹配

相反,我们可以构建自定义图例来显示每个系列的多种颜色。

要构建图例,我们需要添加一个容器来保存图例条目。
我们可以使用位于图表正下方的 <div> 元素。

<div id="chart_div"></div>
<div id="legend_div"></div>

我们可以使用 css 设置图例容器的样式并使用与图表相同的宽度。

#legend_div {
  font-family: Arial;
  font-size: 11px;
  text-align: center;
  width: 920px;
}

在下面的示例中,我从数据 table 中提取每个系列的颜色。
使用样式列角色中提供的值。
要创建图例内容,我使用以下 html 模板。

一个用于图例条目本身...

<script id="template-legend-entry" type="text/html">
  <div class="legend-entry" data-columnIndex="{{index}}">
    {{colors}}
    <span>{{label}}</span>
  </div>
</script>

还有一个用于为该系列显示的每种颜色...

<script id="template-legend-entry-color" type="text/html">
  <div class="legend-entry-color" style="background-color: {{color}}"></div>
</script>

在这个例子中,数据中只有两行 table,
因此每个图例条目将显示两种颜色。

图例是在图表的 'ready' 事件期间建立的,
所以一旦图表绘制完成,
将显示图例。

在此期间,颜色从数据中提取 table 并用于构建图例条目。

为示例目的添加了一个点击事件,以防您在点击图例条目时想要执行的操作。
在此示例中,选择了图表系列以突出显示单击了哪个图例条目。

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ["","0 times (never)",{"role":"style"},"1 times",{"role":"style"},"2 times",{"role":"style"},"3 times or more",{"role":"style"}],
    ["A class",0.581,"#b4ddfd",0.109,"#84bfef",0.21,"#559ad2",0.1,"#4277a1"],
    ["nationality",0.481,"#ffddba",0.209,"#ffc384",0.25,"#ffac5b",0.06,"#fa993f"]
  ]);

  var options = {
    vAxis: {
      textStyle: {
        fontSize: 11
      },
      titleTextStyle: {
        italic: false
      }
    },
    chartArea: {
      width: '85%',
      top: 30,
      left: '13%'
    },
    bar: {
      groupWidth: '35%'
    },
    legend: {
      position: 'none'
    },
    isStacked: 'percent',
    hAxis: {
      ticks: [0, 1],
      textStyle: {
        fontSize: 13
      },
      minValue: 0,
      maxValue: 1
    },
    width: 920,
    height: '100%'
  };

  var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

  // chart ready event
  google.visualization.events.addListener(chart, 'ready', function () {
    // legend container
    var legend = document.getElementById('legend_div');
    legend.innerHTML = '';

    // build legend from chart data
    var colorPallette = [];
    for (var colIndex = 0; colIndex < data.getNumberOfColumns(); colIndex++) {
      // determine if style column
      if (data.getColumnRole(colIndex) === 'style') {
        // save colors for entire series (all rows)
        var seriesColors = '';
        for (var rowIndex = 0; rowIndex < data.getNumberOfRows(); rowIndex++) {
          seriesColors += renderTemplate('template-legend-entry-color', {
            color: data.getValue(rowIndex, colIndex)
          });
        }

        // add legend for series (all colors)
        legend.insertAdjacentHTML('beforeEnd', renderTemplate('template-legend-entry', {
          colors: seriesColors,
          index: colIndex - 1,
          label: data.getColumnLabel(colIndex - 1)
        }));
      }
    }

    // add click event to legend entries
    var legendEntries = legend.getElementsByClassName('legend-entry');
    Array.prototype.forEach.call(legendEntries, function(entry) {
      entry.addEventListener('click', function (e) {
        // find legend entry
        var entry = e.target || e.srcElement;
        if (entry.className.toLowerCase() !== 'legend-entry') {
          entry = entry.parentNode;
        }

        // get data table column index from legend entry
        var columnIndex = parseInt(entry.getAttribute('data-columnIndex'));

        // display legend entry that was clicked
        document.getElementById('message_div').innerHTML = 'legend entry clicked = ' + data.getColumnLabel(columnIndex);

        // select chart series
        chart.setSelection([{row: null, column: columnIndex}]);
      }, false);
    });
  });

  // render html template
  function renderTemplate(templateId, templateProps) {
    var content = document.getElementById(templateId).innerHTML;
    for (var handle in templateProps) {
      if (templateProps.hasOwnProperty(handle)) {
        content = content.replace('{{' + handle + '}}', templateProps[handle]);
      }
    }
    return content.trim();
  }

  // draw chart
  chart.draw(data, options);
});
#legend_div {
  font-family: Arial;
  font-size: 11px;
  text-align: center;
  width: 920px;
}

.legend-entry {
  display: inline-block;
  padding: 16px 4px 8px 4px;
}

.legend-entry-color {
  display: inline-block;
  height: 12px;
  width: 12px;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="legend_div"></div>
<div id="message_div"></div>

<script id="template-legend-entry" type="text/html">
  <div class="legend-entry" data-columnIndex="{{index}}">
    {{colors}}
    <span>{{label}}</span>
  </div>
</script>

<script id="template-legend-entry-color" type="text/html">
  <div class="legend-entry-color" style="background-color: {{color}}"></div>
</script>