下面的代码绘制了两个PostScript (.ps)文件,但第二个文件包含了这两行。
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.subplot(111)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
如何告诉matplotlib为第二个情节重新开始?
正如@DavidCournapeau所说,使用figure()。
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.figure()
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")
plt.figure()
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
或subplot(121) / subplot(122)表示同一地块,不同位置。
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(121)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.subplot(122)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")
你试过plt.close()吗?这对我来说很有效,并确保我不会意外地多次保存相同的情节。
代码:
def save_to(root: Path, plot_name: str = 'plot', close: bool = True):
"""
Assuming there is a plot in display, saves it to local users desktop users desktop as a png, svg & pdf.
note:
- ref on closing figs after saving: https://stackoverflow.com/questions/741877/how-do-i-tell-matplotlib-that-i-am-done-with-a-plot
- clf vs cla https://stackoverflow.com/questions/16661790/difference-between-plt-close-and-plt-clf
"""
root: Path = root.expanduser()
plt.savefig(root / f'{plot_name}.png')
plt.savefig(root / f'{plot_name}.svg')
plt.savefig(root / f'{plot_name}.pdf')
if close:
# plt.clf()
# plt.cla()
plt.close()
在我的终极utils lib: https://github.com/brando90/ultimate-utils