打印时Matplotlib挂起

2024-09-30 03:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Matplotlibjust as I have seen at this question在Python中绘制一些datetime对象。在

但是当它到达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,是因为我在Ubuntu服务器上没有X-server,但这不会是问题所在,因为我做了一个简单的范围图,而且数字被正确地保存了,所以我一定是在代码上犯了一些错误。在

有什么帮助吗?在


Tags: fromimportdatetimeasaxstarttimedeltacolor
1条回答
网友
1楼 · 发布于 2024-09-30 03:24:52

问题在于:

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

但我真的不知道为什么。注释这行代码就可以了。在

相关问题 更多 >

    热门问题