我有一個代碼可以繪制每月的總交易量。數據集不包括所有月份(僅從 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 plotplt.bar(months_unique, df_month['Transaction'])plt.suptitle('Transactions over the months', fontsize=25) # Specify the suptitle of the plotplt.title('Using Data from Years October - April', fontsize=20) # Specify the title of the plotplt.xlabel('month', fontsize=20) # Specify the x labelplt.ylabel('number', fontsize=20) # Specify the y labelplt.setp(plt.gca().get_xticklabels(),fontsize=20)plt.setp(plt.gca().get_yticklabels(), fontsize=20)編輯結果如何df_month = df.groupby('Month')['Transaction'].count()?:使用to_frameand后reset_index:
2 回答
慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
最簡單的方法可能是鑄造你month以str避免matplotlib填補缺失的數字:
plt.bar(months_unique.astype(str), df_month['Transaction'])
...
或者干脆讓pandas為您處理繪圖:
df.groupby('Month')['Transaction'].count().plot(kind="bar")
...
plt.show()
千萬里不及你
TA貢獻1784條經驗 獲得超9個贊
在繪圖代碼之前添加以下行。
df_month_for_plot = df_month[df_month['Transaction']!=0]
然后繪圖df_month_for_plot而不是df_month.
添加回答
舉報
0/150
提交
取消
