有 2 个选项是可能的,一个使用 matplotlib,另一个使用 seaborn,你现在绝对应该使用它,因为它与 Pandas 配合得很好。
使用 matplotlib 的熊猫
您必须创建一个包含您设置的许多列和行的子图。它给出一个数组axes
在一维中,如果nrows
or ncols
设置为 1,否则为 2-D。然后,将此对象提供给 Pandas 绘图方法。
如果类别数量未知或较多,则需要使用循环。
import pandas as pd
import matplotlib.pyplot as plt
fig, axes = plt.subplots( nrows=1, ncols=2, sharey=True )
df.loc[ df["ID"] == 1, 'Value' ].plot.bar( ax=axes[0] )
df.loc[ df["ID"] == 2, 'Value' ].plot.bar( ax=axes[1] )
plt.show()
![Output matplotlib/Pandas](https://i.stack.imgur.com/mJohm.png)
熊猫与seaborn
Seaborn是我所知道的最令人惊奇的图形工具。功能catplot当您设置参数时,可以根据列的值绘制一系列图表col
。您可以选择绘图类型kind
.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
df['index'] = [1,2,3] * 2
sns.catplot(kind='bar', data=df, x='index', y='Value', col='ID')
plt.show()
![Output Pandas/Seaborn](https://i.stack.imgur.com/eN0CL.png)
我添加了一栏index
为了与df.plot.bar
。如果您不想删除x='index'
它会显示一个带有错误的独特栏。
![Seaborn combines the values by category](https://i.stack.imgur.com/6beh8.png)