Matplotlib在绘图时挂起

时间:2014-03-20 16:17:36

标签: python matplotlib

我试图用Matplotlib just as I have seen at this question在Python中绘制一些日期时间对象。

但是当它进入savefig调用时,它会被卡住。这是我的代码:

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)

我使用Agg,因为我在没有X-server的情况下工作到Ubuntu Server机器,但这不是问题,因为我制作了一个简单的范围图并且图形保存正确,所以我必须在代码上犯一些错误。

任何帮助?

1 个答案:

答案 0 :(得分:0)

看起来问题在于:

ax.xaxis.set_major_locator(MinuteLocator(0, interval=15))

但我真的不知道为什么。在评论该行时,代码可以正常工作。