Google图表中的自定义图例多种颜色 [英] Custom Legend multiple colors in Google Chart

查看:53
本文介绍了Google图表中的自定义图例多种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临无法将此图表的默认图例颜色自定义为多种颜色的问题,请帮助我。 这是image描述我的问题,我正在使用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);

请帮帮我,我死锁了。

推荐答案

谷歌图表上的标准图例不会显示多种颜色。
事实上,在使用样式列角色时,
图例将与数据表的样式列中使用的颜色不匹配。

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

若要构建图例,我们需要添加一个容器来容纳图例条目。
我们可以使用恰好位于图表下方的<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;
}

在下面的示例中,我从数据表中提取每个系列的颜色。
使用样式列"角色"中提供的值。
要创建图例内容,我使用以下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>

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

图例是在图表的'ready'事件期间构建的
那么图表一画完,
将显示图例。

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

添加单击事件是出于示例目的,以防您在单击图例条目时要执行某些操作。
在此示例中,选择图表系列以突出显示单击的图例条目。

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>

这篇关于Google图表中的自定义图例多种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆