如何在Google折线图中制作趋势线?

时间:2018-03-19 11:37:57

标签: web google-visualization

我正在尝试在我的网站中使用trendline并希望将其设为虚线,但lineDashStyle在trendline选项下无效。是否有可能使趋势线破灭?

2 个答案:

答案 0 :(得分:0)

没有用于修改趋势线短划线样式的标准图表选项 但是,可以在图表的'ready'事件

上手动更改图表

趋势线将由svg <path>元素表示,一旦找到,
将属性stroke-dasharray设置为您想要的短划线样式

path.setAttribute('stroke-dasharray', '5, 5');

(MDN网络文档 - &gt; stroke-dasharray

请参阅以下工作片段,
趋势线的颜色用于查找<path>元素,
使用图表选项设置颜色 - &gt; trendlines.n.color
其中n是趋势线的系列索引......

&#13;
&#13;
google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Date', 'Value'],
    [new Date(2017, 02,10),100],
    [new Date(2017, 02,21),150],
    [new Date(2017, 02,28),160],
    [new Date(2017, 03,07),150],
    [new Date(2017, 03,14),125],
    [new Date(2017, 03,23),130],
    [new Date(2017, 03,31),135],
    [new Date(2017, 04,07),140],
    [new Date(2017, 04,26),145],
    [new Date(2017, 05,03),130],
    [new Date(2017, 05,10),150],
    [new Date(2017, 05,17),165],
    [new Date(2017, 05,25),175],
    [new Date(2017, 06,05),180],
    [new Date(2017, 06,12),100]
  ]);

  var options = {
    chartArea: {
      bottom: 48,
      height: '100%',
      left: 48,
      right: 16,
      top: 48,
      width: '100%'
    },
    colors: ['#c3d5bc'],
    hAxis: {
      format: 'M/d/yy',
      slantedText: 'true'
    },
    height: '100%',
    legend: {
      alignment: 'start',
      position: 'top'
    },
    trendlines: {
      0: {
        color: '#344f35',
        type: 'linear'
      }
    },
    width: '100%'
  };

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

  // change trendline to dashed
  google.visualization.events.addListener(chart, 'ready', function () {
    var pathElements = container.getElementsByTagName('path');
    Array.prototype.forEach.call(pathElements, function(path) {
      if (path.getAttribute('stroke') === options.trendlines[0].color) {
        path.setAttribute('stroke-dasharray', '5, 5');
      }
    });
  });

  chart.draw(data, options);
});
&#13;
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
&#13;
&#13;
&#13;

注意:不会显示对图表进行的手动更改,
使用图表方法时 - &gt; getImageURI - 生成图表的图像
请改用html2canvas ...

答案 1 :(得分:0)

可以用 css 完成,按颜色搜索:

google-chart path[stroke='#f2994a'] {
  stroke-dasharray: 6, 6;
}