格式化时间时,Pyplot滴答消失

时间:2018-02-15 10:07:02

标签: python matplotlib graph visualization

我使用matplotlib每周绘制一系列值 我创建的数据框(见下面的代码)如下所示:

Dataframe: df_dates   

| Name_Of_index |       |  
|------------   |----   |  
| 2017-01-22    | 13    |  
| 2017-01-29    | 0     |  
| 2017-02-05    | 5     |  
| 2017-02-12    | 37    |    

Freq: W-SUN, dtype: int64

我的代码应该为每周/时间戳的数字绘制条形图。

def plot_contact_with_waters_per_week(dataframe, target_name,contact_with_water_value='contact_with_water', date_col='TBL_DAT'):
   df_contact_with_waters=dataframe[dataframe[target_name]==contact_with_water_value]
   contact_with_waters_per_week=pd.Series((df_contact_with_waters[target_name].values),index=df_contact_with_waters[date_col]).resample(rule='W').count()
   axis_now=contact_with_waters_per_week.plot(kind='bar')
   axis_now.set_ylabel("Total number of contact_with_waters per week")
   axis_now.xaxis_date() 
   axis_now.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=SU))
   axis_now.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
   plt.show()

困扰我的是,只要我格式化x轴,所有刻度都会变得不可见。 Plot of Time Series without xaxis Ticks

现在,如果我只删除三个xaxis行:

   axis_now.xaxis_date() 
   axis_now.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=SU))
   axis_now.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

我确实得到了带有时间戳的情节,但是它们有全长并且看起来不漂亮: Plot of Time Series with ugly xaxis Ticks

现在,我想我在格式化时间戳时犯了一个错误,你能看看并给我一些建议吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

如果有人遇到同样的问题,这里的代码就是:

def plot_contact_with_waters_per_week(dataframe, target_name,contact_with_water_value='contact_with_water', date_col='TBL_DAT'):
   df_contact_with_waters=dataframe[dataframe[target_name]==contact_with_water_value]
   contact_with_waters_per_week=pd.Series((df_contact_with_waters[target_name].values),index=df_contact_with_waters[date_col]).resample(rule='W').count()
   fig, ax = plt.subplots()
   plt.bar(height=contact_with_waters_per_week,left=contact_with_waters_per_week.index,width=3)
   plt.ylabel("Total number of contact_with_waters per week")
   ax.xaxis_date() 
   ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=SU))
   ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
   my_xticks = ax.get_xticks()
   my_xticks_biweekly=my_xticks[::2].copy()
   plt.xticks(my_xticks_biweekly,visible=True, rotation="vertical")
   plt.show()

非常感谢ImportanceOfBeingErnest