如何用单个Google Charts数据集生成双图表并配置系列与轴
用单个Google Charts DataTable实现双图表配置(无数据冗余)
你完全可以复用同一个DataTable生成两个图表,核心是通过图表选项中的hAxis指定不同横轴字段,配合series和vAxes的索引映射,实现系列与纵轴的绑定,无需复制数据集。
步骤1:创建共享的DataTable
先构造一份包含所有字段的数据集,不用复制:
const data = google.visualization.arrayToDataTable([ ['Time', 'Height', 'Speed', 'Flightpath'], [[6, 0, 0], 100, 50, 0], // timeofday格式:[时,分,秒] [[6, 1, 0], 250, 80, 10], [[6, 2, 0], 400, 120, 20], [[6, 3, 0], 600, 100, 30], [[6, 4, 0], 500, 70, 40] ]);
步骤2:配置第一个图表「高度与速度随时间变化」
横轴用Time(DataTable第0列),Height和Speed分别绑定到两个纵轴:
const chart1Options = { title: '高度与速度随时间变化', hAxis: { dataColumn: 0, // 指定横轴为Time列(索引0) title: '时间' }, // 定义两个纵轴的样式 vAxes: { 0: { title: '高度(m)' }, 1: { title: '速度(km/h)', textStyle: { color: '#e67e22' } } }, // 映射系列到对应纵轴 series: { 0: { targetAxisIndex: 0 }, // Height列(索引1)对应纵轴0 1: { targetAxisIndex: 1, color: '#e67e22' } // Speed列(索引2)对应纵轴1 }, legend: { position: 'top' } }; // 初始化并绘制第一个图表 const chart1 = new google.visualization.LineChart(document.getElementById('chart1')); chart1.draw(data, chart1Options);
步骤3:配置第二个图表「高度与速度随飞行路径变化」
横轴换成Flightpath(DataTable第3列),复用同一份数据,只调整横轴和对应选项:
const chart2Options = { title: '高度与速度随飞行路径变化', hAxis: { dataColumn: 3, // 指定横轴为Flightpath列(索引3) title: '飞行路径距离(km)' }, vAxes: { 0: { title: '高度(m)' }, 1: { title: '速度(km/h)', textStyle: { color: '#e67e22' } } }, series: { 0: { targetAxisIndex: 0 }, // 同样Height对应纵轴0 1: { targetAxisIndex: 1, color: '#e67e22' } // Speed对应纵轴1 }, legend: { position: 'top' } }; // 初始化并绘制第二个图表 const chart2 = new google.visualization.LineChart(document.getElementById('chart2')); chart2.draw(data, chart2Options);
关键配置说明
hAxis.dataColumn:直接指定使用DataTable中的某一列作为横轴,无需修改数据集结构series数组的索引:对应DataTable中除横轴外的列顺序(比如第一个图表横轴是0列,series[0]对应第1列Height,series[1]对应第2列Speed)targetAxisIndex:指定该系列绑定到哪个纵轴(0或1,对应vAxes中的键)vAxes:通过索引定义多个纵轴的标题、颜色等样式,实现双轴区分
HTML容器
需要在页面中准备两个图表容器:
<div id="chart1" style="width: 800px; height: 400px;"></div> <div id="chart2" style="width: 800px; height: 400px;"></div>
内容的提问来源于stack exchange,提问作者maze1961
相关产品推荐
相关产品推荐

