java 画图保存图片_将绘图保存到图像文件,而不是使用Matplotlib显示它
回答(15)
2 years ago
我使用了以下內容:
import matplotlib.pyplot as plt
p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05), ncol=2, fancybox=True, shadow=True)
plt.savefig('data.png')
plt.show()
f.close()
plt.close()
我發現在保存圖形后使用plt.show非常重要,否則它將無法工作 . figure exported in png
2 years ago
如果像我一樣使用Spyder IDE,則必須禁用交互模式:
plt.ioff()
(此命令隨科學啟動自動啟動)
如果要再次啟用它,請使用:
plt.ion()
2 years ago
#write the code for the plot
plt.savefig("filename.png")
該文件將保存在與運行的python / Jupyter文件相同的目錄中
2 years ago
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x*x, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
2 years ago
解決方案 :
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')
如果您確實要顯示圖像以及保存圖像,請使用:
%matplotlib inline
在 import matplotlib 之后
2 years ago
如果您不喜歡“當前”圖的概念,請執行以下操作:
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)
2 years ago
解決方案是:
pylab.savefig('foo.png')
2 years ago
正如其他人所說, plt.savefig() 或 fig1.savefig() 確實是保存圖像的方式 .
但是我發現在某些情況下(例如Spyder有 plt.ion() :交互模式= On),總會顯示數字 . 我通過強制關閉我的巨型循環中的數字窗口來解決這個問題,所以我在循環期間沒有一百萬個開放數字:
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png') # save the figure to file
plt.close(fig) # close the figure
2 years ago
其他答案都是正確的 . 但是,我有時會發現我想稍后打開圖形對象 . 例如,我可能想要更改標簽大小,添加網格或進行其他處理 . 在一個完美的世界中,我只需重新運行生成繪圖的代碼,并調整設置 . 唉,世界并不完美 . 因此,除了保存為PDF或PNG之外,我還添加:
with open('some_file.pkl', "wb") as fp:
pickle.dump(fig, fp, protocol=4)
像這樣,我可以稍后加載圖形對象并操縱設置 .
我還為堆棧中的每個函數/方法寫出了包含源代碼和 locals() 字典的堆棧,以便稍后我可以準確地告訴生成該圖的內容 .
注意:要小心,因為有時這種方法會產生巨大的文件 .
2 years ago
有一點需要注意:如果您使用 plt.show 并且它應該在 plt.savefig 之后,或者您將給出一個空白圖像 .
一個詳細的例子:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
2 years ago
你可以這樣做:
plt.show(hold=False)
plt.savefig('name.pdf')
并且記得在關閉GUI圖之前讓savefig完成 . 這樣您就可以預先看到圖像 .
或者,您可以使用 plt.show() 查看它然后關閉GUI并再次運行腳本,但這次將 plt.show() 替換為 plt.savefig() .
或者,您可以使用
fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')
2 years ago
在使用plot()和其他函數創建所需內容之后,您可以使用這樣的子句在繪制到屏幕或文件之間進行選擇:
import matplotlib.pyplot as plt
fig = plt.figure(figuresize=4, 5)
# use plot(), etc. to create your plot.
# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)
if save_file:
plt.savefig(save_file)
plt.close(fig)
else:
plt.show()
2 years ago
他們說阻止數字彈出的最簡單方法是使用非交互式后端(例如Agg),通過 matplotib.use() ,例如:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
我個人更喜歡使用 plt.close( fig ) ,從那以后你可以選擇隱藏某些數字(在循環期間),但仍然顯示循環后數據處理的數字 . 它可能比選擇非交互式后端要慢 - 如果有人測試過那么會很有趣 .
UPDATE :對于Spyder,你通常不能以這種方式設置后端(因為Spyder通常會提前加載matplotlib,阻止你使用 matplotlib.use() ) .
相反,使用 plt.switch_backend('Agg') ,或關閉Spyder首選項中的“啟用支持”并自行運行 matplotlib.use('Agg') 命令 .
從這兩個提示:one,two
2 years ago
雖然問題已得到解答,但我想在使用savefig時添加一些有用的提示 . 文件格式可以由擴展名指定:
savefig('foo.png')
savefig('foo.pdf')
將分別給出柵格化或矢量化輸出,兩者都可能有用 . 此外,你會發現 pylab 在圖像周圍留下了一個慷慨的,通常是不受歡迎的空白區域 . 刪除它:
savefig('foo.png', bbox_inches='tight')
2 years ago
import matplotlib.pyplot as plt
plt.savefig("image.png")
在Jupyter Notebook中,您必須刪除plt.show()并將plt.savefig()與其余的plt-code一起包含在一次單元格中 . 圖像仍將顯示在筆記本中 .
總結
以上是生活随笔為你收集整理的java 画图保存图片_将绘图保存到图像文件,而不是使用Matplotlib显示它的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cocoa mysql_基本MySQL查
- 下一篇: java实现扫地agent_如何实现ja