以下是一个使用Bokeh库创建堆叠条形图的示例代码:
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6
from bokeh.transform import factor_cmap
# 创建数据
fruits = ['Apples', 'Pears', 'Bananas', 'Oranges', 'Kiwis']
years = ['2015', '2016', '2017']
data = {'fruits' : fruits,
'2015' : [2, 1, 4, 3, 2],
'2016' : [5, 3, 3, 2, 4],
'2017' : [3, 2, 4, 4, 5]}
# 创建堆叠条形图
p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year",
toolbar_location=None, tools="")
p.vbar_stack(years, x='fruits', width=0.9, color=factor_cmap('fruits', palette=Spectral6, factors=fruits), source=data,
legend_label=years)
# 设置图例位置
p.legend.location = "top_left"
p.legend.title = 'Years'
# 显示图表
output_notebook()
show(p)
这段代码会生成一个堆叠条形图,其中每个水果在每年的数量以不同的颜色堆叠在一起。使用vbar_stack()
函数创建堆叠条形图,通过传递不同的颜色调色板和数据源来为不同的年份着色。图例显示不同年份的数据。