Matplotlib savefig不保存轴

scyqe7ek  于 2023-10-24  发布在  其他
关注(0)|答案(6)|浏览(200)

我试图保存一个在IPython内联中工作正常的图形,但不将图形与轴和标题一起保存到磁盘。
我在matplotlibrc中默认使用TKAgg后端。
有什么想法可能会出错吗?我已经清楚地设置了xlabel,刻度线在IPython内联图中正确工作。

  1. import matplotlib.pylab as plt
  2. x = [1,2,3,3]
  3. y = map(lambda(x): x * 2, x)
  4. fig = plt.figure()
  5. ax = fig.add_axes([0,0,1,1])
  6. ax.set_title("bleh")
  7. ax.set_xlabel("xlabel")
  8. ax.plot(x, y, 'r--')
  9. fig.savefig("fig.png")

gopyfrb3

gopyfrb31#

在开始时定义fig = plt.figure(figsize=(15,10)),将文件保存为.jpg并设置bbox_inches='tight'-plt.savefig('filename.jpg',bbox_inches='tight', dpi=150)为我解决了这个问题。bbox_inches='tight'似乎修复了裁剪问题,但它不适用于. png。

x0fgdtte

x0fgdtte2#

可能是facecolor,我在jupyter实验室工作,facecolor默认设置为黑色,所以你看不到轴,即使它们正在绘制。

  1. fig = plt.figure(facecolor=(1, 1, 1))

将背景色设置为白色。

fcipmucu

fcipmucu3#

您正在将轴设置为从图的左下方开始,并填满整个图。没有空间放置轴标签或标题。尝试以下操作:

  1. import matplotlib.pylab as plt
  2. x = [1,2,3,3]
  3. y = map(lambda(x): x * 2, x)
  4. fig = plt.figure()
  5. ax = fig.add_axes([0.1,0.1,0.75,0.75]) # axis starts at 0.1, 0.1
  6. ax.set_title("bleh")
  7. ax.set_xlabel("xlabel")
  8. ax.plot(x, y, 'r--')
  9. fig.savefig("fig.png")

5m1hhzi4

5m1hhzi44#

我在使用xmlyter notebook和命令:%matplotlib notebook时遇到了同样的问题。该图在notebook中正确显示,但在使用fig.savefig()保存时无法打印轴和标题。我将%matplotlib notebook改为%matplotlib inline,这解决了问题。

x6h2sr28

x6h2sr285#

我能够解决这个问题(在visual studio代码jupyter扩展中),方法是将格式从“png”改为“jpg”,沿着参数“plt.subplots(tight_layout=True plots”。

wbgh16ku

wbgh16ku6#

我使用的是Yutter Notebook,只需将.png更改为.jpg,我的问题就解决了。

  1. # changing the size of figure to 2X2
  2. plt.figure(dpi=100, figsize=(15, 10))
  3. plt.grid()
  4. #display(plt.plot(year1, ratio1))
  5. x = np.arange(1900, 2020, 5)
  6. plt.xticks(x)
  7. plt.title(ttile)
  8. plt.xlabel('Year')
  9. plt.ylabel('Ratio')
  10. plt.plot(year,ratio)
  11. plt.savefig('books_read.jpg', dpi = 300)

Saved Image from the Code

相关问题