Reputation: 13254
I am trying to plot some datetime objects in Python with Matplotlib, just as I have seen at this question.
But when it gets to the savefig call, it gets stuck. This is my code:
import matplotlib as mpl
mpl.use('Agg') # Matplotlib backend to use without an X-server
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MinuteLocator
from datetime import datetime
from datetime import timedelta
def plot_scenario(outages_start, outages_end, prediction_start, prediction_end,
filepath=None):
fig = plt.figure()
ax = fig.add_subplot(111)
y = [0.3, 0.7]
timelines(ax, y[0], prediction_start, prediction_end, color='r')
for xstart, xstop in zip(outages_start, outages_end):
timelines(ax, y[1], xstart, xstop)
ax.xaxis_date()
myFmt = DateFormatter('%d %H:%M')
ax.xaxis.set_major_formatter(myFmt)
ax.xaxis.set_major_locator(MinuteLocator(0, interval=15))
# Delta needed to adjust the xlimits
delta = (prediction_end - prediction_start) / 10
#ax.set_yticks(['Prediction', 'Outages']) #Not working
ax.set_ylim(0, 1)
ax.set_xlim(prediction_start - delta, prediction_end + delta)
ax.set_xlabel('Time')
if filepath is None:
fig.show()
else:
# Save plot as PNG
fig.savefig(filepath) # Gets stuck here
print 'PGN file saved at ' + filepath
# plot timelines at y from xstart to xstop with a given color
def timelines(current_axis, y, xstart, xstop, color='b'):
current_axis.hlines(y, xstart, xstop, color, lw=4)
current_axis.vlines(xstart, y+0.03, y-0.03, color, lw=2)
current_axis.vlines(xstop, y+0.03, y-0.03, color, lw=2)
if __name__ == '__main__':
prediction_start = datetime(2014, 3, 20) + timedelta(hours=12)
prediction_end = prediction start + timedelta(hours=10)
outages_start = []
outages_end = []
outages_start.append(datetime(2014, 3, 20) + timedelta(hours=14))
outages_end.append(datetime(2014, 3, 20) + timedelta(hours=15))
outages_start.append(datetime(2014, 3, 20) + timedelta(hours=17))
outages_end.append(datetime(2014, 3, 20) + timedelta(hours=18))
path = '/home/myuser/test.png'
plot_scenario(outages_start, outages_end, prediction_start, prediction_end, path)
I'm using Agg since I'm working without X-server into an Ubuntu Server machine, but this can't be the problem because I made a simple range plot and the figure was saved correctly, so I must be making some mistake at the code.
Any help?
Upvotes: 0
Views: 1234
Reputation: 13254
Looks like the problem is in the line:
ax.xaxis.set_major_locator(MinuteLocator(0, interval=15))
But I don't really know why. Commenting that line, the code works.
Upvotes: 1