【问题标题】:Automatically saving plot, python, matplotlib自动保存绘图、python、matplotlib
【发布时间】:2014-10-03 13:45:15
【问题描述】:

我想在完成后保存我的情节。我尝试过这样的事情:

import matplotlib.pyplot as plt
import os

plt.ion()
x = []
y = []
home = os.sep.join((os.path.expanduser('~'), 'Desktop'))
home1 = home + '\nowy'

for i in range(0,20):
    x.append(i)
    y.append(i+2)

    plt.plot(x, y, 'g-', linewidth=1.5, markersize=4)
    plt.axis(xmin = 0,xmax = 200,ymin=0,ymax=200)
    plt.show()
    plt.pause(0.1)
plt.pause(5)
plt.savefig(os.sep.join(home1 + '1'),format = 'png') 

但它不起作用。还有一个错误:

[Errno 22] invalid mode ('wb') or filename: 'C\\:\\\\\\U\\s\\e\\r\\s\\\\\\M\\i\\c\\h\\a\\l\\\\\\D\\e\\s\\k\\t\\o\\p\\\n\\o\\w\\y\\p\\l\\o\\t\\1.png'

谁能告诉我如何在“home1”方向准确地保存这个情节,好吗?我已经搜索了一段时间的解决方案,但没有任何效果。

【问题讨论】:

    标签: python matplotlib plot save


    【解决方案1】:

    试试os.path.join:

    plt.savefig(os.path.join(os.path.expanduser('~'), 'Desktop', 'nowy1.png')) 
    

    您也可以使用os.sep.join,这会使您的代码更加兼容。它可能看起来像这样:

    plt.savefig(os.sep.join([os.path.expanduser('~'), 'Desktop', 'nowy1.png']))
    

    【讨论】:

    • 非常感谢你:)
    • @Maq92:你的代码中有几个plt.pause调用,在保存当前数字之前尝试删除最后一个。
    • 不,最后的停顿必须在那里。我在“更新”grapht(获取新点并绘制它)之前谈论这个时间。我要用它画一些大图,不想等几个小时:)有什么办法可以提升它吗?
    • @Maq92 添加新数据时,是否需要在每一步都绘制当前图形?根据您要显示的数据大小,plt.draw 只需要一些时间,至少据我所知,您无法加快速度。但是对于您在这里的示例代码,您需要等待的时间实际上应该由plt.pause 调用决定。
    • 这将是一个基于从外部设备接收的数据绘制(并实时更新)图表的程序。嗯,好的,谢谢你的帮助:)
    【解决方案2】:

    如果您要自动运行它,最好使用 OO 接口而不是状态机接口:

    import matplotlib.pyplot as plt
    import os
    
    plt.ion()
    x = []
    y = []
    home = os.path.join(os.path.expanduser('~'), 'Desktop')
    home1 = os.path.join(home, 'nowy')
    
    # create the figure and axes
    fig, ax = plt.subplots(1, 1)
    ax.set_xlim(0, 200)
    ax.set_ylim(0, 200)
    
    # create the line2D artist
    ln, = ax.plot(x, y, 'g-', linewidth=1.5, markersize=4)
    # do the looping
    for i in range(0,20):
        # add to the data lists
        x.append(i)
        y.append(i+2)
        # update the data in the line2D object
        ln.set_xdata(x)
        ln.set_ydata(y)
        # force the figure to re-draw
        fig.canvas.draw()
        # pause, let the gui re-draw it's self
        plt.pause(0.1)
    # pause again?
    plt.pause(5)
    # save the figure
    fig.savefig(os.path.join(home1,  '1'),format='png') 
    

    [未测试,因为在 RC3 中发现了一个不相关的错误]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2019-09-13
      • 2011-12-10
      • 2020-04-27
      • 2020-06-12
      • 1970-01-01
      • 2020-10-17
      相关资源
      最近更新 更多