I have a timeseries dataset of a month. I am plotting it using matplotlib in python however I am not able to display all the dates of a month on the x-axis. I want the x-axis to show full dates. The dataset looks something like this:
Date and Time Temperature
7/1/2022 0:00 25.4
7/1/2022 0:15 23.2
7/1/2022 0:30 22.5
7/1/2022 0:45 23
7/1/2022 1:00 22.3
7/1/2022 1:15 22
And here is my code for plotting the data:
fig, ax = plt.subplots(figsize=(25, 10))
df_0.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 1')
df_1.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 2')
df_2.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 3')
df_3.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 4')
df_4.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 5')
plt.xlabel('Date and Time of the month - July')
plt.ylabel('Temperature')
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m.%d.%Y"))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
plt.gcf().autofmt_xdate()
plt.show()
The data I has was in one single dataframe. I divided into different dataframes in order plot it on a weekly basis. Here is the output:
I have tried using ax.axis method, DateFormatter and DayLocator however none of these is having any effect on the graph. I want the axis to show full dates like 22-07-2022 etc. And I can confirm that the Date and Time column is in datetime format.
CodePudding user response:
Convert the date/time column to datetime data type, then use x_compat = True
to enforce Python datetime compatibility, which in turn allows to use mdates formatter correctly.
Given
df
Date and Time Temperature
0 7/1/2022 0:00 25.4
1 7/1/2022 0:15 23.2
2 7/1/2022 0:30 22.5
3 7/1/2022 0:45 23.0
4 7/1/2022 1:00 22.3
5 7/1/2022 1:15 22.0
that can look like
df['Date and Time'] = pd.to_datetime(df['Date and Time'], format="%m/%d/%Y %H:%M")
fig, ax = plt.subplots(figsize=(25, 10))
df.plot(kind='line', x='Date and Time', y='Temperature', ax=ax, label='Week 1',
x_compat=True)
plt.xlabel('Date and Time of the month - July')
plt.ylabel('Temperature')
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m.%d.%Y"))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
plt.show()