自动保存图表,python,matplotlib

3 投票
2 回答
2569 浏览
提问于 2025-04-18 16:45

我想在完成我的图表后保存它。我试过这样做:

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”这个方向吗?我找了解决办法很久了,但都没成功。

2 个回答

4

如果你打算让这个程序自动运行,使用面向对象的接口会比状态机接口更好:

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') 

[因为发现了一个与此无关的bug,所以没有测试]

4

试试用 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']))

撰写回答