Cyrine Ezzahra Cyrine Ezzahra - 3 months ago 9
Python Question

Change xaxis range values in a plot with matplotlib

I am doing a plot of dataframe df_no_missing.

df_no_missing.head()
TIMESTAMP datetime64[ns]
P_ACT_KW float64
PERIODE_TARIF object
P_SOUSCR float64
SITE object
TARIF object
depassement float64
dtype: object


Out[236]:

TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR SITE TARIF depassement date time

2015-08-01 23:10:00 248.0 HC 425.0 ST GEREON TURPE_HTA5 0.0 2015-08-01 23:10:00


2015-08-01 23:20:00 244.0 HC 425.0 ST GEREON TURPE_HTA5 0.0 2015-08-01 23:20:00


2015-08-01 23:30:00 243.0 HC 425.0 ST GEREON TURPE_HTA5 0.0 2015-08-01 23:30:00


2015-08-01 23:40:00 238.0 HC 425.0 ST GEREON TURPE_HTA5 0.0 2015-08-01 23:40:00

2015-08-01 23:50:00 234.0 HC 425.0 ST GEREON TURPE_HTA5 0.0 2015-08-01 23:50:00


I did a plot representing the variation of P_ACT_KW and P_SOUSCR with TIMESTAMP.
The python code is below :

fig = plt.figure(figsize=(11, 6), dpi=100)
ax = fig.add_subplot(111)
yearFmt = mdates.DateFormatter("%H:%M:%S")

ax.xaxis.set_major_formatter(yearFmt)
sns.set_style("darkgrid")
x = pd.to_datetime(df_no_missing.TIMESTAMP, format="%h:%m")
y = df_no_missing.P_ACT_KW
z = df_no_missing.P_SOUSCR
plt.plot(x, y, marker='o', label='P_SOUSCR')
plt.plot(x, z, marker='o', linestyle='--', color='g', label='P_ACT_KW')
plt.xlabel('temps')
plt.ylabel('puissance')
plt.title('variation de la puissance')
plt.legend()
plt.show()


I get a plot like this (the attached image) enter image description here

My question is how can I show the timestamp in the xaxis, I mean I need the see the timestamp indicated in the dataframe for exampel here : 23:10:00, 23:20:00 , 23:30:00, 23:40:00, 23:50:00. and not 01:00 , 04:00, 07:00 ...

Thank you if you can help me

Bests

Answer

You can add set_major_locator before set_major_formatter:

import matplotlib.dates as mdates

yearFmt = mdates.DateFormatter("%H:%M:%S")

minx = pd.to_datetime( '2015-08-01 23:10:00' )
minx = pd.to_datetime( '2015-08-01 23:50:00' )

ax.set_xlim( [ minx, maxx ] )
ax.xaxis.set_major_locator( mdates.MinuteLocator(byminute=range(0,60,10)) )  
ax.xaxis.set_major_formatter( yearFmt )
Comments