谷歌饼图:如何更改图例中的线条颜色?

时间:2013-11-19 10:39:30

标签: javascript charts google-api google-visualization pie-chart

我有一个饼图,其中图例的位置设置为“已标记”,因此切片描述和值放在饼图旁边的一行上。我现在要做的是将切片与匹配图例连接的线的颜色更改为相应切片的颜色。

legend.textStyle或其他允许此更改的地方是否有任何属性?

这是我的代码:

function drawVisualization() {
  // Create and populate the data table.
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', 11],
    ['Eat', 2],
    ['Commute', 2],
    ['Watch TV', 2],
    ['Sleep', 7]
  ]);

  // Create and draw the visualization.
  new google.visualization.PieChart(document.getElementById('visualization')).
      draw(data, {
        width: '800',
        height: '400',
        title: "So, how was your day?",
        legend: {
          position: 'labeled',
          textStyle: {
            color: 'gray'    // sets the text color
          }
        }
      });
}

非常感谢!

问候, 岸堤

1 个答案:

答案 0 :(得分:5)

使用svg技术呈现Google图表,因此可以设置样式。虽然您将不得不为元素使用一些硬编码索引。

Google pie chart with colored lines

我已经实现了一个函数replaceLabelColors,它可以获取相应的g标记并替换它们的属性。

对于您的示例,可以使用它:

var dataLength = data.J.length; // 5
var 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"];

var chartId = "visualization"
var chart = new google.visualization.PieChart(document.getElementById(chartId));
chart.draw(data, { width: '800', height: '400', title: "So, how was your day?", colors: colors, legend: { position: 'labeled', textStyle: { color: 'gray' }}});

var graphics = document.getElementById(chartId).querySelectorAll("svg > g");
// graphics[0] is title, graphics[1..n] are pie slices, and we take label area which is graphics[n+1]
var labelsGraphics = graphics[dataLength+1].childNodes; 

// get svg graphics and replace colors
var replaceLabelColors = function(){
    var colorIndex = 0;
    for (var i = 0; i < labelsGraphics.length; i++) {
        if (i % 2 == 0) {
            // skip even indexes
            continue;
        } else {
            var currentLine = labelsGraphics[i];
            currentLine.childNodes[0].setAttribute("stroke", colors[colorIndex]); // <path stroke="#636363" ...>
            currentLine.childNodes[1].setAttribute("fill", colors[colorIndex]); // <circle fill="#636363" ...>
            colorIndex++;
        }
    }
}

replaceLabelColors();
google.visualization.events.addListener(chart, "onmouseover", replaceLabelColors);
google.visualization.events.addListener(chart, "onmouseout", replaceLabelColors);