plt.savefig在调用plt.show之前保存空数字

2024-06-24 12:50:17 发布

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

我正在Jupyter实验室工作,并试图保存该图。函数savefig()在show()之前调用,该图在笔记本中显示得很好,但保存的pdf是空白的

原始代码有点长,基本上是这样的:

ylim = 8

ax = plt.subplot(321)
ax.plot(list(range(80)), np.random.randn(80), color='purple', alpha=0.5)
ax.set_xlim([0, 79])
ax.set_ylim([-ylim, ylim])
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

ax = plt.subplot(323)
ax.axvspan(59, 79, facecolor='pink', alpha=0.5)
ax.plot(list(range(80)), np.random.randn(80), color='g', alpha=0.5)
ax.set_xlim([0, 79])
ax.set_ylim([-ylim, ylim])
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

ax = plt.subplot(325)
ax.axvspan(59, 79, facecolor='pink', alpha=0.5)
ax.plot(list(range(60)), np.random.randn(80), color='b', alpha=0.5)
ax.set_xlim([0, 79])
ax.set_ylim([-ylim, ylim])
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

ax = plt.subplot(122)
ax.imshow(image)
plt.gca().set_axis_off()
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top = 1, bottom = 0, right = 3, left = 1, 
            hspace = 0, wspace = 0)
plt.margins(0,0)

plt.savefig('figure.pdf', pad_inches=0, dpi=500, transparent=True)
plt.show()

The saved figure is blank

But well shown in the notebook