问题
I am using matplotlib to plot a serie of values per week.
The dataframe I create (see code below) looks like this:
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
My code is supposed to draw a bar plot for number per week/timestamp.
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()
The thing that bothers me is that as soon as I format the x-axis, all ticks become invisible.
Now, if I just delete the three xaxis lines:
axis_now.xaxis_date()
axis_now.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=SU))
axis_now.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
I do get my plot with timestamps, but they have the full length and do not look pretty:
Now, I suppose I make a mistake in formatting my timestamps, can you please have a look and give me some advice? It would be much appreciated.
回答1:
In case anybody ever runs into the same issue, here is the code that worked:
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()
A big thank you to ImportanceOfBeingErnest!
来源:https://stackoverflow.com/questions/48804513/pyplot-ticks-disappear-when-formatting-time