Setting a date for the x-axis label in Matplotlib

Viewed 262

I have a code in which I create a data frame from the data of a bunch of sensors, select which type of sensor I wish to observe, and the period over which I would like to observe this sensor. The data is then plotted and saved to an Excel file. The following is a snippet of what my data frame looks like.

         Site Name               Sensor Display Name   Readings Datetime  
342   100 Adelaide  EY_VAV_31_05 - Space Temperature 2021-01-01 00:06:00   
343   100 Adelaide  EY_VAV_31_05 - Space Temperature 2021-01-01 00:21:00   
344   100 Adelaide  EY_VAV_31_05 - Space Temperature 2021-01-01 00:36:00   
345   100 Adelaide  EY_VAV_31_05 - Space Temperature 2021-01-01 00:52:00   
346   100 Adelaide  EY_VAV_31_05 - Space Temperature 2021-01-01 01:06:00   

My issue is that when I plot the data, I would like to get the dates of each day I observe to be the labels for my X-axis. Instead, I get the number of hours since the beginning of the data. I'm a little new to matplotlib, and don't fully understand how I can fix this. The following is the code used to plot everything.

chosen['Readings Value'].plot()
plt.xlabel('Hour')
plt.ylabel('Sensor Reading')
plt.show()

I don't want to use pd.groupby to reorganize the data by day, as I need to keep all of the data for every hour. Any help will be appreciated, thank you.

1 Answers

I am going to assume that "Readings Datetime" in your dataframe is a single column; (that is, the column contains values like 2021-01-01 00:06:00).

The column should also be type Pandas Timestamp. If not, then you can convert it as follows:

df['Readings Datetime'] = pd.to_datetime(df['Readings Datetime'])

Matplotlib has its own datetime type. You may already know this and have converted, but in case not, do the following:

import matplotlib.dates  as mdates
xdates = mdates.date2num([dtm.to_pydatetime() for dtm in df['Readings Datetime']])

where xdates is the variable you will use to populate your x-axis data.

Then to format the x-asis with only the dates:

formatter = mdates.DateFormatter('%Y-%b-%d')  # or similar format string
ax.xaxis.set_major_formatter(formatter)       # `ax` is your Axes object

I just now looked more closely at your code:

chosen['Readings Value'].plot()
plt.xlabel('Hour')
plt.ylabel('Sensor Reading')
plt.show()

Assuming chosen is your dataframe, you appear to be using a combination of Pandas (which uses matplotlib under the hood) and matplotlib directly (plt) to plot your data. This can result in some confusing situations, because Pandas makes certain assumptions when plotting, and takes some of the control away from you.

You can avoid this by either doing all of your plotting directly in matplotlib,

or continue using Pandas to plot, but before calling chosen[...].plot() call

fig, ax = plt.subplots()

to gain access to the Figure and Axes objects.

Then you can call ax.xaxis.set_major_formatter() as shown above. There is also an example here that also shows how to reformat the x-axis when using Pandas to plot with datetimes on the x-axis.

Related