基础柱状图
柱状图是一种用于呈现离散数据之间比较的图表。柱条的长度与分类数据成正比。
要设置柱状图,你需要将 series 的 type 设置为 'bar'。
简单示例
我们从一个基础的柱状图开始。
option = { xAxis: { data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: {}, series: [ { type: 'bar', data: [23, 24, 18, 25, 27, 28, 25] } ] };
在这种情况下,x 轴是类目轴。因此,你需要为 'xAxis' 定义一些相应的值。同时,y 轴的数据类型是数值型。y 轴的范围将由 'series' 中的 data 自动生成。
多系列柱状图
你可以使用一个系列(series)来表示一组相关的数据。要在同一个图表中显示多个系列,你需要在 series 下再添加一个数组。
option = { xAxis: { data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: {}, series: [ { type: 'bar', data: [23, 24, 18, 25, 27, 28, 25] }, { type: 'bar', data: [26, 24, 18, 22, 23, 20, 27] } ] };
自定义柱状图
样式
通过 'series.itemStyle' 来设置柱状图的样式是一个好主意。SCI 的描述
- 柱条的颜色(
'color'); - 柱条的描边颜色(
'borderColor')、宽度('borderWidth')、类型('borderType'); - 柱条的圆角半径(
'barBorderRadius'); - 透明度(
'opacity'); - 阴影类型(
'shadowBlur'、'shadowColor'、'shadowOffsetX'、'shadowOffsetY')
这是一个例子
option = { xAxis: { data: ['A', 'B', 'C', 'D', 'E'] }, yAxis: {}, series: [ { type: 'bar', data: [ 10, 22, 28, { value: 43, // Specify the style for single bar itemStyle: { color: '#91cc75', shadowColor: '#91cc75', borderType: 'dashed', opacity: 0.5 } }, 49 ], itemStyle: { barBorderRadius: 5, borderWidth: 1, borderType: 'solid', borderColor: '#73c0de', shadowColor: '#5470c6', shadowBlur: 3 } } ] };
在这个例子中,我们通过相应 series 的 'itemStyle' 定义了柱状图的样式。完整的配置项及其用法,请查阅配置项手册:series.itemStyle。
柱条的宽度和高度
你可以使用 barWidth 来改变柱条的宽度。例如,在下面的例子中,'barWidth' 被设置为 '20%'。这表示每个柱条的宽度是类目宽度的 20%。由于每个系列中有 5 个数据,20% 的 'barWidth' 意味着占整个 x 轴的 4%。
option = { xAxis: { data: ['A', 'B', 'C', 'D', 'E'] }, yAxis: {}, series: [ { type: 'bar', data: [10, 22, 28, 43, 49], barWidth: '20%' } ] };
此外,barMaxWidth 限制了柱条的最大宽度。对于一些较小的值,你可以为柱条声明一个最小高度:barMinHeight。当数据的对应高度小于该限制时,ECharts 将使用 'barMinHeight' 作为替代高度。
柱间距
有两种柱间距。一种是同一类目下不同系列之间的间距:barGap。另一种是不同类目之间的间距:barCategoryGap。
option = { xAxis: { data: ['A', 'B', 'C', 'D', 'E'] }, yAxis: {}, series: [ { type: 'bar', data: [23, 24, 18, 25, 18], barGap: '20%', barCategoryGap: '40%' }, { type: 'bar', data: [12, 14, 9, 9, 11] } ] };
在这个例子中,barGap 是 '20%'。这意味着同一类目下柱条之间的距离是柱条宽度的 20%。例如,如果我们设置 barCategoryGap 为 '40%',那么柱条两侧的间距将占据类目宽度的 40%(与柱条宽度相比)。
通常,如果设置了 'barGap' 和 barCategoryGap,则不必明确指定 barWidth。如果需要确保在图表很大时柱条不会太宽,可以尝试使用 barMaxWidth 来限制柱条的最大宽度。
在同一个笛卡尔坐标系中,该属性将被多个柱状图系列共享。为确保它在图表上生效,请在坐标系的最后一个柱状图系列上设置该属性。
为柱条添加背景色
有时你可能想改变柱条的背景色。在 ECharts v4.7.0 之后,可以通过 'showBackground' 启用此功能,并由 'backgroundStyle'进行配置。
option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [120, 200, 150, 80, 70, 110, 130], type: 'bar', showBackground: true, backgroundStyle: { color: 'rgba(220, 220, 220, 0.8)' } } ] };