Issue
I'm having some trouble formatting the x-axis label. I'd like to format the label to show the dates to show the hours but also the date in a YYYY-MM-DD.
Code:
df1.plot.line(y='val1', ax=ax1);
df2.plot.line(y='val1', ax=ax2, legend=False);
plt.suptitle('Some plot ' + str(time[0]) + ' - ' + str(time[1]), fontsize=16, y=1);
#ax1.yaxis.grid(False)
#ax2.yaxis.grid(False)
ax1.grid(linestyle='--', linewidth=0.75)
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.set_xlabel('Date-Time')
#ax2.xaxis.set_major_locator(md.MonthLocator())
#ax2.xaxis.set_major_formatter(md.DateFormatter('%Y-%m'))
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.grid(linestyle='--', linewidth=0.75)
ax1.legend(bbox_to_anchor=(1.05, 1));
ax2.legend(bbox_to_anchor=(1.05, 1));
ax1.set_title('ClientAB=0');
ax2.set_title('ClientAB=1');
I would like the hours to remain that way but I'd like the Date to change from 16-May to 2022-05-16. I've tried using formatter from mdates but it displayed the year incorrectly like 3226 instead of 2022.
A sample of how the index looks like in my dataframe
Solution
Inspired by the answer above, I found a way to adjust the formatting as well as the frequency of x-ticks for a line plot when dealing with time series.
ax.xaxis.set_major_locator(md.HourLocator(interval=8))
ax.xaxis.set_major_formatter(
md.DateFormatter("%Y-%d-%m %H:%M")
)
ax.set_xlim(pd.Timestamp('2022-06-03 16:00:00'), pd.Timestamp('2022-06-06 10:00:00'))
For example the piece of code above helps you set how often you'd like your ticks to show up e.g. every 8 hour. The formatter used in this case will plot the date in short form (yyyy/mm/dd) and the hour and minute.
Answered By - Geosphere
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.