gpt4 book ai didi

python - Matplotlib 填充缺失的 Tic 标签

转载 作者:行者123 更新时间:2023-11-28 18:40:17 27 4
gpt4 key购买 nike

我有一个 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,
)

结果图如下所示: enter image description here一切看起来都很好,除了 xtic 标签,我希望它们根据它的值间隔开(即,“-9”不应该在图的中间,或者“0”不应该紧挨着“5” , ETC)。事实上,由于我的 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))

产生这个(想要的)结果:

enter image description here

注意:每个条形的宽度设置为 1.0,并且它们已移动 -0.5 以便使每个条形在刻度线上方居中。

最佳答案

看起来 Pandas 还没有(尚未)为其条形图包装器功能提供显式放置条形图位置的能力。 0.14.0“新增功能”表示“条形图的坐标现在位于整数值(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 列表的变化产生了下面的图(为简单起见,我删除了额外的轴)。

bar chart at exact locations

注意:pandas 0.14.0下操作df_list[i].index-0.4会报错,这个bug在0.15.1已经修复.您可以通过先将索引转换为普通的 numpy 数组来解决这个问题,或者只升级 pandas。

关于python - Matplotlib 填充缺失的 Tic 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018570/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com