如何隐藏在matplotlib条形图中没有值的条

问题描述 投票:0回答:2

我有一个代码可以绘制每月的总交易次数。数据集不包括所有月份(仅从10到4)。但是,当我绘制它时,它仍然包括5到9个月的时间(当然,没有柱)。我想隐藏它们,因为它们甚至都不是数据集的一部分。

这是我得到的:

enter image description here

这是我的代码

df_month = df.groupby('Month')['Transaction'].count()
months_unique = df.Month.unique()
df_month = df_month.reindex(months_unique, axis=0) # This line and the line above are to reorder the months as they are in the original dataframe (the first line orders them starting from 1. wrong)

df_month = df_month.to_frame()
df_month.reset_index(level=0, inplace=True) #resetting the index istead of having the month as an index. 

plt.figure(figsize=(20, 10)) # specify the size of the plot

plt.bar(months_unique, df_month['Transaction'])
plt.suptitle('Transactions over the months', fontsize=25) # Specify the suptitle of the plot
plt.title('Using Data from Years October - April', fontsize=20) # Specify the title of the plot
plt.xlabel('month', fontsize=20) # Specify the x label
plt.ylabel('number', fontsize=20) # Specify the y label

plt.setp(plt.gca().get_xticklabels(),fontsize=20)
plt.setp(plt.gca().get_yticklabels(), fontsize=20)



编辑

df_month = df.groupby('Month')['Transaction'].count()的结果如何?:

enter image description here

使用to_framereset_index后:

enter image description here

python pandas matplotlib
2个回答
0
投票

在绘图代码之前添加以下行。


0
投票

最简单的方法可能是将month强制转换为str,以避免matplotlib填写丢失的数字:

© www.soinside.com 2019 - 2024. All rights reserved.