【发布时间】:2021-12-03 20:29:31
【问题描述】:
我有一个包含几列的数据框 (df),其中两列在每一行中存储一个列表:
Index list1 list2
A [ 0.09173306 0.12331911 0.20057651 ] [ 0.3128322 0.27153913 ]
D [ 0.03861522 0.10524985 ] [ 0.37265687 0.48347806 ]
E [ 0.02124905 0.01149118 ] [ 0.04348405 0.17057435 0.37838683 0.37481453 ]
我想使用pandas 内置的plot 函数将这些列表绘制为条形图。
使用
df.list1.apply(lambda x:x[0]).plot(kind='bar', width=0.9, ax=bar_ax)
我可以绘制每个列表的第一个元素。但是,尝试
df.list1.plot(kind='bar', width=0.9, ax=bar_ax)
导致以下错误:
Empty 'DataFrame': no numeric data to plot
我想做的是,(1) 将两个列表绘制成一个图,如下所示:
df[['list1','list2']].plot(kind='bar', width=0.9, ax=bar_ax)
并且 (2) 还将每个列表的第一个元素仅绘制成一个条形图,我可以这样做:
df.list1.apply(lambda x:x[0]).plot(kind='bar', width=0.9, ax=bar_ax, color='blue')
df.list2.apply(lambda x:x[0]).plot(kind='bar', width=0.9, ax=bar_ax, color='red')
但是,这会导致条形图彼此重叠(而不是堆叠!) - 我希望将它们分组。
【问题讨论】:
标签: python list pandas plot dataframe