Sigmun
Sigmun

Reputation: 1002

how to round date format on x axis in matplotlib

I am trying to plot a curve in between two others filled and as soon as I have these two "plots", my x-axis become strange.

Here is my MWE:

import matplotlib.pyplot as plt
from matplotlib import dates as mdates
import datetime
import numpy as np

dates=[u'0600', u'0630', u'0700', u'0730', u'0800', u'0830', u'0900', u'0930', u'1000', u'1030']#["0800","0830","0900"]

x=[datetime.datetime.strptime(h,'%H%M') for h in dates]
y=np.arange(len(x))
tmin=y/2.
tmax=y*2.

fig, ax = plt.subplots()
ax.plot(x,y,'r')
ax.fill_between(x,tmin,tmax)

hfmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(hfmt)

fig.autofmt_xdate()
plt.savefig('plot.png')
plt.show()

Plot with bad x-axis

where the x-axis should looks like

Plot with good x-axis

which can easily be obtained by commenting one of the plot or fill_between command line.

Any idea of how to have the second x-axis in the first figure ?

Upvotes: 1

Views: 713

Answers (1)

Christoph
Christoph

Reputation: 1557

The easiest way would probably be to use

ax.x_axis.set_major_locator(mdates.MinuteLocator(byminute=[0,30]))

Upvotes: 3

Related Questions