我想从此数据框中创建一个堆积条形图,其中 x 轴是每个唯一的日期,堆积条形图是从提供者列下的每个数值中提取的值。
当我创建数据透视表时,数据会聚合具有相同名称的列。 如果我将“provider”作为新列进行旋转,那么这将产生 5 列和 14 行。 问题是 bokeh vbar_stack 不接受不同的列和行。列数和行数必须相同。但是,如果没有数据聚合,我无法制作数据透视表。
我可以转换这些数据并使用 bokeh 包创建堆叠条形图吗?
代码:
pivot_df = grouped_df.pivot_table(index=['date'], columns='provider', values='num_youths', aggfunc='first', fill_value=0)
pivot_df.reset_index(inplace=True)
source = ColumnDataSource(pivot_df)
providers = pivot_df.columns[1:]
# Create the figure
p = figure(x_range=pivot_df['date'].unique(), plot_height=350, title="Number of Youths Funded by Provider Each Month",
toolbar_location=None, tools="")
# Add stacked bars to the figure
p.vbar_stack(stackers=providers, x='date', width=0.9, color=["blue", "red"], source=source,
legend_label=providers)
错误信息: ValueError:广播的关键字参数序列必须与堆栈器的长度相同
你必须以正确的方式处理 pandas DataFrame。
下面的示例是您的数据的最小示例。如果并非所有组在每个日期都有值,我会使用
groupby
和 unstack
以及填充模式来添加零。
然后我删除返回的 DataFrame 的多重索引。
import pandas as pd
df = pd.DataFrame({
'date': ['Aug 23', 'Aug 23', 'Dec 23'],
'provider': ['A', 'B', 'C'],
'num_youths': [1, 3, 4]
}
)
df
>>> df
date provider num_youths
0 Aug 23 A 1
1 Aug 23 B 3
2 Dec 23 C 4
# groupby and fill with zeor
stacked = df.groupby(['date','provider']).sum().unstack(fill_value=0)
>>> stacked
num_youths
provider A B C
date
Aug 23 1 3 0
Dec 23 0 0 4
# drop multi index for columns and index
stacked.columns = stacked.columns.droplevel()
provider = list(stacked.columns)
stacked = stacked.reset_index()
要获取散景所需的数据,您必须使用
to_dict
调用 orient="list"
。
data = stacked.to_dict(orient='list')
数据格式正确,所以只需调用
figure()
和vbar_stack
即可。此代码的大部分来自文档中的堆叠条形示例。
from bokeh.plotting import figure, show, output_notebook
from bokeh.palettes import HighContrast3
output_notebook()
p = figure(x_range=data['date'], height=250,
toolbar_location=None, tools="hover", tooltips="@date $name @$name")
p.vbar_stack(provider, x='date', width=0.9, color=HighContrast3, source=data,
legend_label=provider)
show(p)