我有一个Pandas数据帧列表(例如):
df1 = pd.DataFrame({'Number':[-9,-8,0,1,2,3], 'A':[3,6,4,1,7,19], 'B':[2,4,4,0,7,1]})
df1.set_index('Number',inplace=True)
df2 = pd.DataFrame({'Number':[0,5,6,7,8,9], 'A':[8,7,3,5,2,15], 'B':[1,7,1,1,1,3]})
df2.set_index('Number',inplace=True)
df_list = [df1, df2] #In reality there are more than two in the list
我会尝试用Matplotlib来绘制它们:
nrow = 2
ncol = 2
fig, axs = plt.subplots(nrow,ncol)
for i in range(nrow*ncol):
#Convert 1D to 2D
row = i / ncol
col = i % ncol
if i >= len(df_list):
axs[row,col].axis('off')
else:
df_list[i]['A'].plot(kind='bar',
ax=axs[row,col],
ylim=(0,20),
xlim=(-10,10),
figsize=(20,15),
color=('green'),
legend=False,
)
df_list[i]['B'].plot(kind='bar',
ax=axs[row,col],
ylim=(0,20),
xlim=(-10,10),
figsize=(20,15),
color=('yellow'),
legend=False,
)
由此产生的地块如下:
一切看起来都很好,除了xtic标签,我希望按照它的值来分隔(也就是说,"-9“不应该在图的中间,或者"0”不应该就在"5“旁边,等等)。事实上,由于我的x-范围大约是(-10,10),我希望这个完整的范围显示在x轴上,并使彩色条形图按其“数字”相应地定位。我想出的一个可能的解决方案是使用Pandas来填充(-10,10)中缺少的值,但我认为有一个更好/更明显的方法来处理这个问题。我只是没能找到那个解决方案。
更新:
感谢Ajean(和JD Long)下面的响应,我现在使用这个Matplotlib代码:
df_list = [df1, df2]
nrow = 2
ncol = 2
fig, axs = plt.subplots(nrow,ncol,figsize=(20,15))
for i in range(nrow*ncol):
#Convert 1D to 2D
row = i / ncol
col = i % ncol
if i >= len(df_list):
axs[row,col].axis('off')
else:
axs[row,col].bar(np.array(df_list[i].index)-0.5, df_list[i]['A'], width=1, color='green')
axs[row,col].bar(np.array(df_list[i].index)-0.5, df_list[i]['B'], width=1, color='yellow')
axs[row,col].set_xlim([-10,10])
axs[row,col].set_ylim([0,20])
axs[row,col].xaxis.set_ticks(np.arange(-10, 11, 1))
它产生了这样(想要的)结果:
注意:每个条形的宽度被设置为1.0,它们被移动到-0.5,以便在抽搐标记之上将每个条形线居中。
发布于 2014-11-19 09:33:00
看起来Pandas还没有(还)赋予其条形图包装器功能,无法显式地放置条形图位置。0.14.0 "What's New“表示”条形图的坐标现在位于整数值(0.0、1.0、2.0 .)上“,据我所知,在0.15.1中没有任何变化。
因此,我将跳过Pandas接口(您肯定会使用它),直接使用Matplotlib。
nrow = 1
ncol = 2
fig, axs = plt.subplots(nrow,ncol)
for i in range(nrow*ncol):
if i >= len(df_list):
axs[i].axis('off')
else:
# You could theoretically turn this into a loop over your columns
# with appropriate widths and offsets
axs[i].bar(df_list[i].index-0.4, df_list[i]['A'], width=0.4, color='green')
axs[i].bar(df_list[i].index, df_list[i]['B'], width=0.4, color='yellow')
上面使用定义的DataFrame列表进行的代码更改生成了下面的图(为了简单起见,我去掉了额外的轴)。
注意事项:熊猫0.14.0下的操作df_list[i].index-0.4
会产生一个错误,这个错误已经在0.15.1中得到了修复。您可以先将索引转换为正常的numpy数组,或者只是升级熊猫。
发布于 2014-11-19 06:19:52
你问了一个很好的问题。谢谢你有一个可重复的例子,这使它更容易帮助。
问题是潘达斯条形图代码在x轴上假定分类数据。很明显你没有分类数据。但是,通过Pandas绘图接口(据我所知)告诉Matplotlib没有什么好方法。
对我来说,最明显的解决办法就是你提出的增加价值的办法。我很可能会加入。我将现有的dataframe加入到一个索引中,该索引在x轴上具有我想要的所有值,并使用how='outer'
选项进行连接。
https://stackoverflow.com/questions/27018570
复制相似问题