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

Python 如何隐藏matplotlib条形图中没有值的条形图,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个代码,可以绘制每个月的总交易量。数据集不包括所有月份(仅从10到4个月)。然而,当我绘制它时,它仍然包括5到9个月(当然,没有酒吧)。我想隐藏它们,因为它们甚至不是数据集的一部分 以下是我得到的: 这是我的密码 df_month = df.groupby('Month')['Transaction'].count() months_unique = df.Month.unique() df_month = df_month.reindex(months_unique, axis=0)

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

以下是我得到的:

这是我的密码

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()
的结果如何

在使用
到_帧
重置_索引
后:


在打印代码之前添加以下行

df_month_for_plot = df_month[df_month['Transaction']!=0]

然后,将
df\u month\u绘制为
而不是
df\u month
最简单的方法可能是将
month
转换为
str
,以避免
matplotlib
填充缺失的数字:

plt.bar(months_unique.astype(str), df_month['Transaction'])
...
或者干脆让
pandas
为您处理打印:

df.groupby('Month')['Transaction'].count().plot(kind="bar")
...
plt.show()

尝试将
months\u unique
转换为类别
months\u unique=df.Month.unique()。aType('category')
@fmarm不起作用。上面写着“数据类型”类别“未理解”。你能展示一下你的
df_月
在执行
df.groupby('month')['Transaction'].count()
?@RedowanDelowar post-edited后的样子吗?你为什么不让
pandas
帮你处理呢<代码>df.groupby('Month')['Transaction'].count().plot(kind=“bar”);plt.show()
。它给出了完全相同的数据帧。因为没有一个月(在数据框中)事务首先是0。