4

I want to make a plot with matplotlib, that looks like this:

screenshot

The problem is I am getting the data from mySQL and the date is a string therefore. I want to assign a date to each y-value. The current date format is like that: Y-M-d h:m:s

Can you help me with how I must format this into a valid datetime, or is it possible to plot strings on x-axis and float on y-axis?

1 Answer 1

6

It is normally best to first convert your data to datetime format. It can then be formatted using a DateFormatter as follows:

import matplotlib
import matplotlib.pyplot as plt
from datetime import datetime

x_orig = ['2015-12-29 15:01:25', '2015-12-29 15:02:08', '2015-12-29 15:02:13', '2015-12-29 15:04:18']
x = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x_orig]
y = ['7.1', '7.4', '9.4', '10.2']

xs = matplotlib.dates.date2num(x)
hfmt = matplotlib.dates.DateFormatter('%Y-%m-%d\n%H:%M:%S')

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.patch.set_facecolor('lightgrey')
ax.xaxis.set_major_formatter(hfmt)
ax.set_title('Titel des Reports')
ax.set_xlabel('datum')
ax.set_ylabel('2MTemperatur')
plt.setp(ax.get_xticklabels(), size=8)
ax.plot(xs, y, linewidth=2)
ax.scatter(xs, y)
plt.grid()
plt.show()

This would give you the following:

matplotlib screenshot

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.