[英]Plotting Bokeh bar chart using sum of grouped Pandas column
我正在嘗試創建一個條形圖來查看哪些商店在我的數據集中的收入最高。 使用默認值 Pandas plot 我可以在一行中完成:
df.groupby('store_name')['sale_value'].sum().sort_values(ascending=False).head(20).plot(kind='bar')
但是這個圖表不是很互動,我看不到確切的值,所以我想嘗試使用 Bokeh 創建它,並且能夠將鼠標懸停在一個條上並查看確切的數量,例如。
我嘗試執行以下操作,但只得到一個空白頁:
source = ColumnDataSource(df.groupby('store_name')['sale_value'])
plot = Plot()
glyph = VBar(x='store_name', top='sale_value')
plot.add_glyph(source, glyph)
show(plot)
如果我將源更改為 ColumnDataSource(df.groupby('store_name')['sale_value'].sum()) 我會得到 'ValueError: expected a dict or pandas.DataFrame, got store_name'
如何使用 Bokeh 通過鼠標懸停創建此圖表?
假設這是我們的 DataFrame:
df = pd.DataFrame({'store_name':['a', 'b', 'a', 'c'], 'sale_value':[4, 5, 2, 4]})
df
>>>
store_name sale_value
0 a 4
1 b 5
2 a 2
3 c 4
現在可以使用您的方法創建條形圖。
首先我們必須做一些導入和預處理:
from bokeh.models import ColumnDataSource, Grid, LinearAxis, Plot, VBar, Title
source = ColumnDataSource(df.groupby('store_name')['sale_value'].sum().to_frame().reset_index())
my_ticks = [i for i in range(len(source.data['store_name']))]
my_tick_labels = {i: source.data['store_name'][i] for i in range(len(source.data['store_name']))}
groupby
的部分有一些變化。 添加了.sum()
並將其重置為具有升序索引的 DataFrame。
然后你可以創建一個plot。
plot = Plot(title=Title(text='Plot'),
plot_width=300,
plot_height=300,
min_border=0,
toolbar_location=None
)
glyph = VBar(x='index',
top='sale_value',
bottom=0,
width=0.5,
fill_color="#b3de69"
)
plot.add_glyph(source, glyph)
xaxis = LinearAxis(ticker = my_ticks,
major_label_overrides= my_tick_labels
)
plot.add_layout(xaxis, 'below')
yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
show(plot)
我還想向您展示我更喜歡的第二種方法。
from bokeh.plotting import figure, show
plot = figure(title='Plot',
plot_width=300,
plot_height=300,
min_border=0,
toolbar_location=None
)
plot.vbar(x='index',
top='sale_value',
source=source,
bottom=0,
width=0.5,
fill_color="#b3de69"
)
plot.xaxis.ticker = my_ticks
plot.xaxis.major_label_overrides = my_tick_labels
show(plot)
我更喜歡第二個,因為它更短一些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.