- 可视化是关于讲述一个故事,并以清晰简洁的方式呈现数据以传达该故事。因此,更清楚的是每个图都有相同的 x 轴顺序。
- 查看您的可视化的人应该能够快速辨别出哪个商店的哪个产品的总销售额最高,但如果每个轴的产品类别的顺序不同,这并不容易
- 这可以通过
pandas.DataFrame.plot 使用pandas.DataFrame.pivot_table 整形数据来完成。
-
通过
python 3.8.11、matplotlib 3.4.2、seaborn 0.11.2 和pandas 1.3.1 测试。
import pandas as pd
import matplotlib.pyplot as plt
# using the sample data; reshape df
dfp = df.pivot_table(index='product', columns='store', values='sales', aggfunc='sum')
# display(dfp)
store store1 store2 store3
product
A 9303.543781 15323.422183 20738.561588
B NaN 7549.028221 NaN
C 13976.321362 22350.050356 9865.392344
D 6905.455849 3183.767513 6010.941242
# plot
dfp.plot(kind='bar', subplots=True, layout=(1, 3), figsize=(8, 4), legend=False, rot=0,
sharey=True, title='Store Sales by Product', ylabel='Total Sales')
plt.show()
- 这个演示更清晰,没有子图(删除
subplots=True)
dfp.plot(kind='bar', rot=0, figsize=(5, 3), title='Store Sales by Product', ylabel='Total Sales')
plt.show()
- 切换
index 和columns 的类别讲述了不同的故事
dfp = df.pivot_table(index='store', columns='product', values='sales', aggfunc='sum')
dfp.plot(kind='bar', rot=0, figsize=(5, 3), title='Product Sales by Store', ylabel='Total Sales')
plt.show()
- 使用
.catplot 可以在没有.groupby 或.pivot_table 的情况下完成此操作,因为kind='bar' 有一个estimator 参数。
- 使用
col=
import seaborn as sns
sns.catplot(kind='bar', data=df, col='store', x='product', y='sales',
order=sorted(products), col_order=sorted(stores), estimator=sum, ci=False, height=3)
plt.show()
- 使用
hue=
- 仅供参考,此图的随机数据 (
df) 与其他图不同。
sns.catplot(kind='bar', data=df, hue='store', x='product', y='sales', height=3,
col_order=sorted(stores), estimator=sum, ci=False, order=sorted(products))
plt.show()