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

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

这是我得到的:

http://img2.mukewang.com/62df4eac000167cb20571098.jpg

这是我的代码


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()?:

http://img3.mukewang.com/62df4eb60001d06d05320307.jpg

使用to_frameand后reset_index


http://img2.mukewang.com/62df4ec0000129e503200441.jpg

长风秋雁
浏览 95回答 2
2回答

慕哥9229398

最简单的方法可能是铸造你month以str避免matplotlib填补缺失的数字:plt.bar(months_unique.astype(str), df_month['Transaction'])...或者干脆让pandas为您处理绘图:df.groupby('Month')['Transaction'].count().plot(kind="bar")...plt.show()

千万里不及你

在绘图代码之前添加以下行。df_month_for_plot = df_month[df_month['Transaction']!=0]然后绘图df_month_for_plot而不是df_month.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python