pandas_groupby_nested#

一个分组条形图,使用来自 Auto MPG 数据集 的清理版本。此示例演示了 Pandas GroupBy 对象的自动处理以及使用 factor_cmap 对嵌套因子进行颜色映射。悬停工具提示显示每个条形的信息。

详情

样本数据:

bokeh.sampledata.autompg

Bokeh API:

figure.vbar, bokeh.transform.factor_cmap

更多信息:

使用 pandas

关键词:

条形图,分类,颜色映射,分组,pandas

from bokeh.palettes import MediumContrast5
from bokeh.plotting import figure, show
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.transform import factor_cmap

df.cyl = df.cyl.astype(str)
df.yr = df.yr.astype(str)

group = df.groupby(['cyl', 'mfr'])

index_cmap = factor_cmap('cyl_mfr', palette=MediumContrast5, factors=sorted(df.cyl.unique()), end=1)

p = figure(width=800, height=300, title="Mean MPG by # Cylinders and Manufacturer",
           x_range=group, toolbar_location=None, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")])

p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group,
       line_color="white", fill_color=index_cmap )

p.y_range.start = 0
p.x_range.range_padding = 0.05
p.xgrid.grid_line_color = None
p.xaxis.axis_label = "Manufacturer grouped by # Cylinders"
p.xaxis.major_label_orientation = 1.2
p.outline_line_color = None

show(p)