目前,Google Charts API 没有此内置功能,但通过对 DataTable 和 Chart Options 进行一些改造,您仍然可以实现此目的。
我的解决方案
Stacked Bar 应仅包含 Expenses 和 Profit 的值,为避免包含 Sales 的 Stacked Bar,Sales 数据列中的值表示为零。通过具有类似的数据行创建单独的销售条,但存在销售值,其余为零。需要指定 Date 数据类型以便将所有具有相同日期的条形图分组,如果不执行此操作,则每个具有相同年份的条形图之间将存在间隙。
有关列的日期表示的更多信息,请访问here。
var data = google.visualization.arrayToDataTable([
[ {label: 'Year', id: 'year', type: 'date'},
{label: 'Sales', id: 'Sales', type: 'number'},
{label: 'Expenses', id: 'Expenses', type: 'number'},
{label: 'Profit', id: 'Profit', type: 'number'}],
[{v:new Date('2014'), f:'2014'}, 0, 400, 200],
[{v:new Date('2014'), f:'2014'}, 1000, 0, 0],
[{v:new Date('2015'), f:'2015'}, 0, 460, 250],
[{v:new Date('2015'), f:'2015'}, 1170, 0, 0],
[{v:new Date('2016'), f:'2016'}, 0, 1120, 300],
[{v:new Date('2016'), f:'2016'}, 600, 0, 0],
[{v:new Date('2017'), f:'2017'}, 0, 540, 350],
[{v:new Date('2017'), f:'2017'}, 1030, 0, 0]
]);
为了实现堆积条形,使用了谷歌图表配置选项isStacked: true。为避免垂直轴像带有月份和日期的时间线一样,垂直轴被格式化为使用vAxis: {format: 'yyyy'} 显示年份。有关格式化的更多信息,请访问here。为了避免不同年份条之间的间距,使用了 bar: {groupWidth: '90%'} 功能。
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal', // Required for Material Bar Charts.
hAxis: {format: 'decimal'},
vAxis: {
format: 'yyyy'
},
height: 400,
colors: ['#1b9e77', '#d95f02', '#7570b3'],
isStacked: true,
bar: {groupWidth: '90%'}
};