pwprnt pwprnt - 2 years ago 81
Python Question

plotting dates in matplotlib with NaN values

I have found many questions on this subject, but I still cannot understand the basic steps to plot date information in python.

My timeseries is

>>> datetime_series.shape
>>> datetime_series
array([datetime.datetime(1979, 1, 2, 0, 0),
datetime.datetime(1979, 1, 2, 1, 0),
datetime.datetime(1979, 1, 2, 2, 0), ...,
datetime.datetime(1979, 12, 31, 21, 0),
datetime.datetime(1979, 12, 31, 22, 0),
datetime.datetime(1979, 12, 31, 23, 0)], dtype=object)

My data is

>>> data.shape
#contains np.nan values!!!

My code right now (my commented out is what I have tried...)

fig,ax1 = plt.subplots()
ax1.set_ylabel('Cumulative windspeed over open water [m/s]')
#ax1.set_xlim( ### how do I do this??
plt.title('My title')

This produces a blank plot.

If anyone can walk me through the steps of plotting datetime , I just don't understand where to start, becuase it seems like the documentation and the stackoverflow answers all have different methods.. (for example, using plot_date versus just plt.plot()

Answer Source

I'm not sure why your data isn't being graphed - it should work even with NaN values. Check out this example, you can look at data and datetime_series to see how they compare to your data. As stated in the comments there is an official example on how to use dates in matplotlib - which would definitely be worth looking at.

import matplotlib.pyplot as plt
import datetime
import numpy as np

# Generate some dummy data
N = 500
year = np.random.randint(1950,2000,N)
month = np.random.randint(1,12,N)
day = np.random.randint(1,28,N)

datatime_series = np.array([datetime.datetime(*(dd+(0,0))) for dd in zip(year, month, day)])

data = np.random.random(N)*20000 + (np.linspace(1950,2000,N)/10.)**2

# Now add some NaNs
for i in np.random.randint(0,N-1,int(N/10)):

fig, ax = plt.subplots(1)
ax.plot(datatime_series, data)

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download