How to change date format using matplolib in python


Question

Possible Duplicate:
Creating graph with date and time in axis labels with matplotlib

I don't know how to change the date format when plotting with matplotilib while my data has full date in my dictionary, i only plot hours, minutes, seconds

from datetime import datetime
import matplotlib.pyplot as plt


dico =  {'A01': [(u'11/10/12-08:00:01', 2.0), (u'11/10/12-08:10:00', 10.0), \
                 (u'11/10/12-08:20:01', 5.0), (u'11/10/12-08:30:01', 15.0), \
                 (u'11/10/12-08:40:00', 7.0), (u'11/10/12-08:50:01', 45.0)],
         'A02': [(u'11/10/12-08:00:01', 10.0), (u'11/10/12-08:10:00', 12.0), \
                 (u'11/10/12-08:20:01', 15.0), (u'11/10/12-08:30:01', 10.0), \
                 (u'11/10/12-08:40:00', 17.0), (u'11/10/12-08:50:01', 14.0)]}

x = []
y = []
for key in sorted(dico.iterkeys()):
#in Python3
#for key in sorted(dico.keys()):
   points = [(datetime.strptime(i[0], "%d/%m/%y-%H:%M:%S"), \
               i[1]) for i in dico[key]]
   points.sort()
x, y = zip(*points)
plt.plot(x, y, label=key)  
# plotting
plt.gcf().autofmt_xdate()
plt.legend(loc='upper right')
plt.xlabel('Dates')
plt.ylabel("titre")
plt.title("Modbus")
plt.show()
1
6
7/30/2018 7:35:46 AM

Accepted Answer

The solution:

from matplotlib.dates import DateFormatter
formatter = DateFormatter('%Y-%m-%d %H:%M:%S')
plt.gcf().axes[0].xaxis.set_major_formatter(formatter)
16
10/16/2012 10:16:44 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon