在Google条形图中自定义hAxis刻度线颜色

时间:2018-07-03 12:43:22

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

是否可以更改xAxis栏上刻度线的颜色?

See this image

我想用2000绿色,2500橙色和3000红色做刻度线。

我已经尝试过了,但是似乎不起作用:

ticks: [500, 1000, 1500, {v: 2000, color: "Green"}, {v: 2500, color: "Orange"}, {v: 3000, color: "Red"}]

ticks: [500, 1000, 1500, [2000, "Green"], [2500, "Orange"], [3000, "Red"]]

感谢您的帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

没有用于更改单个刻度线颜色的配置选项

但您可以在图表的'ready'事件中手动更改,
参见以下工作片段...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.arrayToDataTable([
    ['Category', 'value'],
    ['a', 2924],
    ['b', 2075],
    ['c', 2516],
    ['d', 2153],
    ['e', 2348],
    ['f', 1925]
  ]);

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

  google.visualization.events.addListener(chart, 'ready', changeTickColors);

  chart.draw(data, {
    legend: {
      alignment: 'end',
      position: 'top'
    },
    hAxis: {
      ticks: [500, 1000, 1500, 2000, 2500, 3000]
    }
  });

  function changeTickColors() {
    var tickColors = {
      "2,000": "green",
      "2,500": "orange",
      "3,000": "red"
    };

    Array.prototype.forEach.call(container.getElementsByTagName('text'), function(label) {
      if (label.getAttribute('text-anchor') === 'middle') {
        if (tickColors.hasOwnProperty(label.textContent)) {
          label.setAttribute('fill', tickColors[label.textContent]);
        }
      }
    });
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>