1

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', ...]

2

1 Answer 1

11

You can make use mapplotlib's DateFormatter:

  1. Parse your date strings into datetime objects.
  2. Convert your datetime objects into matplotlib numbers using date2num()
  3. Create a DateFormatter() using your desired output format
  4. Apply the DataFormatter() as the major tick format for the x-axis.
  5. 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: matplotlib screenshot

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.