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()
Using the DateFormatter module from matplotlib, you can specify the format that you want to use for the date using the syntax: "%X %X" where each %X element represents a part of the date as follows: %Y - 4 digit year with upper case Y. %y - 2 digit year with lower case y. %m - month as a number with lower case m.
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
MatPlotLib with Python Create a figure and a set of subplots using subplots() method. Plot the dataframe using plot method, with df's (Step 1) time and speed. To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.
matplotlib.pyplot.clf() Function. The clf() function in pyplot module of matplotlib library is used to clear the current figure.
The solution:
from matplotlib.dates import DateFormatter
formatter = DateFormatter('%Y-%m-%d %H:%M:%S')
plt.gcf().axes[0].xaxis.set_major_formatter(formatter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With