Как бы изменить цвет фона в легенде с помощью Google Chart? - PullRequest
0 голосов
/ 12 декабря 2018

Мой текущий код легенды:

legend: {
            position: 'top',
            maxLines: 3,
            textStyle: {
                color: '#969696',
            },
        },

Пример того, как я хотел бы, чтобы он выглядел следующим образом:

Example image

Я не могу найти, как установить цвет фона для каждого отдельного элемента в легенде.

* edit

В настоящее время это выглядит так:

enter image description here

Использование:

        var options = {
          colors: ['#ee7200', '#d6550d', '#f7380c', '#871c03']
        }

* Не могу добавить тег для google-charts-api или google-charts

Ответы [ 2 ]

0 голосов
/ 13 декабря 2018

Стандартные параметры конфигурации для установки цвета фона отдельных записей легенды отсутствуют.
Вам нужно будет вручную изменить <svg> диаграммы в событии 'ready' диаграммы.

для примера, см. Следующий рабочий фрагмент ...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable({
    "cols":[
      {"label": "Month", "type": "string"},
      {"label": "First Approach", "type": "number"},
      {"label": "Follow Up", "type": "number"},
      {"label": "Email or Call", "type": "number"},
      {"label": "Meeting Confirmation", "type": "number"}
    ],
    "rows":[
      {"c": [{"v": "Jan"}, {"v": 4}, {"v": 3}, {"v": 7}, {"v": 8}]},
      {"c": [{"v": "Feb"}, {"v": 5}, {"v": 4}, {"v": 8}, {"v": 9}]},
      {"c": [{"v": "Mar"}, {"v": 6}, {"v": 5}, {"v": 9}, {"v": 4}]}
    ]
  });

  var options = {
    backgroundColor: 'transparent',
    chartArea: {
      backgroundColor: 'transparent',
      bottom: 32,
      height: '100%',
      left: 32,
      right: 16,
      top: 32,
      width: '100%'
    },
    colors: ['#ee7200', '#d6550d', '#f7380c', '#871c03'],
    hAxis: {
      textStyle: {
        color: '#ffffff',
      }
    },
    height: '100%',
    legend: {
      position: 'top',
      maxLines: 3,
      textStyle: {
        color: '#ffffff',
      }
    },
    vAxis: {
      textStyle: {
        color: '#ffffff',
      }
    },
    width: '100%'
  };

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

  // chart ready event
  google.visualization.events.addListener(chart, 'ready', function () {
    // get svg namespace
    var svg = container.getElementsByTagName('svg')[0];
    var svgNS = svg.namespaceURI;

    // save legend labels to use size later
    var legend = [];
    var labels = container.getElementsByTagName('text');
    Array.prototype.forEach.call(labels, function(label) {
      // legend labels will be first in dom, ignore other labels
      if (legend.length >= (data.getNumberOfColumns() - 1)) {
        return;
      }

      // bring legend label to front
      label.setAttribute('id', 'legend-' + legend.length);
      var link = document.createElementNS(svgNS, 'use');
      link.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#legend-' + legend.length);
      svg.appendChild(link);

      // save label
      legend.push(label);
    });

    // increase size of legend rects, find by color
    var legendPosition = 0;
    options.colors.forEach(function (color) {
      var count = 0;
      var rects = container.getElementsByTagName('rect');

      // use first rect found for color, ensure colors are all lowercase
      Array.prototype.forEach.call(rects, function(rect) {
        if ((count === 0) && (rect.getAttribute('fill') === color)) {
          count++;

          // increase size of rect
          rect.setAttribute('height', parseFloat(rect.getAttribute('height')) + 2);
          rect.setAttribute('width', legend[legendPosition].getBBox().width + 16);

          // move legend label within rect
          legend[legendPosition].setAttribute('x', parseFloat(rect.getAttribute('x')) + 8);
          legendPosition++;
        }
      });
    });
  });

  chart.draw(data, options);
  window.addEventListener('resize', function () {
    chart.draw(data, options);
  });
});
.chart {
  background-color: #212f3d;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="chart" id="chart_div"></div>
0 голосов
/ 12 декабря 2018

Вы пробовали

textStyle: {
            color: '#969696',
            backgroundColor: '#0f0f0f'
},

?

...