如何在Google Charts中仅显示趋势线,隐藏原始数据折线?
问题:Google Charts仅显示趋势线、隐藏原始数据折线
我用JQuery结合Google Charts绘制图表,通过PHP从数据库获取数据,目前能生成包含5条数据折线的图表,也实现了基于日期的趋势线。但想只展示各系列的趋势线、隐藏原始数据折线,试了几种方法都不行:
- 移除所有系列会触发“数据不足无法创建图表”的错误
- 设置透明度为0后图表显示异常
尝试过的代码
初始绘制代码:
var chart = new google.visualization.LineChart(document.getElementById(this_kpi + '__' + this_aggreg)); chart.draw(data, options);
尝试用DataView设置样式的代码:
view = new google.visualization.DataView(data); view.setColumns([ 1, 2, 3, 4, 5, { calc: function (data, row) { var opacity = 'opacity: 0;' }, type: 'string', role: 'style' } ]); chart.draw(view, options);
解决方案
直接在图表配置options里给每个数据系列设置lineWidth: 0,同时保留趋势线的配置即可。这种方式不会移除原始数据,只是让原始折线不可见,既不会触发数据不足的错误,又能正常显示趋势线。
示例代码:
// 配置图表选项,重点设置series的lineWidth和trendlines var options = { // 你的其他基础配置(比如标题、坐标轴设置等) title: '仅显示趋势线示例', hAxis: { title: '日期' }, vAxis: { title: '数值' }, // 配置5个系列的趋势线(根据你的实际需求调整参数) trendlines: { 0: { color: '#2196F3', lineWidth: 2 }, 1: { color: '#4CAF50', lineWidth: 2 }, 2: { color: '#FF9800', lineWidth: 2 }, 3: { color: '#F44336', lineWidth: 2 }, 4: { color: '#9C27B0', lineWidth: 2 } }, // 将每个原始数据系列的折线宽度设为0,隐藏原始折线 series: { 0: { lineWidth: 0 }, 1: { lineWidth: 0 }, 2: { lineWidth: 0 }, 3: { lineWidth: 0 }, 4: { lineWidth: 0 } } }; // 使用原始数据直接绘制图表即可 var chart = new google.visualization.LineChart(document.getElementById(this_kpi + '__' + this_aggreg)); chart.draw(data, options);
说明
lineWidth: 0会让原始数据的折线完全隐藏,但数据依然存在,满足图表对数据量的要求- 趋势线的配置可以根据你的需求调整颜色、宽度等样式参数
- 不需要用DataView的style角色来设置透明度,这种方式对折线图的样式控制不适用,直接在series里设置lineWidth是更可靠的方法
内容的提问来源于stack exchange,提问作者VGO
相关产品推荐
相关产品推荐

