Issue
I try to plot a graph with a set of data. The y-axis is no problem, it's simple floats.
Problem is the x-axis: Its data is formatted by datetime to '%Y-%m-%d %H:%M:%S'
. When trying to plot it occurs of course the error of no float possible... I tried quite many ways and it still wouldn't work...
So input so far are two arrays:
x is ['2016-02-05 17:14:55', '2016-02-05 17:14:51', '2016-02-05 17:14:49', ...]
.
y is ['35.764299', '20.3008', '36.94704', ...]
Solution
You can make use mapplotlib's DateFormatter
:
- Parse your date strings into
datetime
objects. - Convert your
datetime
objects into matplotlib numbers usingdate2num()
- Create a
DateFormatter()
using your desired output format - Apply the
DataFormatter()
as the major tick format for the x-axis. - Also convert your float strings to actual floats.
Try the following:
import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime
x_orig = ['2016-02-05 17:14:55', '2016-02-05 17:14:51', '2016-02-05 17:14:49']
x = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x_orig]
y = ['35.764299', '20.3008', '36.94704']
xs = matplotlib.dates.date2num(x)
y_float = list(map(float, y)) # Convert y values to floats
hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.xaxis.set_major_formatter(hfmt)
plt.setp(ax.get_xticklabels(), rotation=15)
ax.plot(xs, y_float)
plt.show()
This would display the following:
Answered By - Martin Evans
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.