使用有序数据使用 matplotlib 创建子图

Creating subplots using matplotlib using ordered data

我的数据框看起来像

d = {'First': ['A','A','A','B','B','C'], 
      'Second': ['B', 'C', 'B', 'B', 'B', 'A']
df = pd.DataFrame(data = d)

我希望能够为第一个值中的每个值创建条形图,最好使用子图,它显示第二个值的数量。我试过使用 df.groupby('First')['Second'].agg('value_counts').plot(kind = 'bar, subplots = True) 但这只会生成一个图形。如果可能的话,我还想让图表展示组的百分比或按字母顺序排列。

试试这个:

df.groupby('First')['Second']\
  .agg('value_counts')\
  .unstack('First')\
  .plot.bar(subplots=True, figsize=(10,8))

输出:

关键是拆开您希望子图表示的列。数据框中的每一列都应生成一个子图。