Matplotlib savefig 不保存轴

Ric*_*odd 11 matplotlib

我正在尝试保存一个在 IPython 内联中工作正常的图形,但没有将包含轴和标题的图形保存到磁盘。

我在 matplotlibrc 中默认使用 TKAgg 后端

任何想法这里可能会出现什么问题?我已经清楚地设置了 xlabel 和刻度线在 IPython 内嵌图中正常工作。

   import matplotlib.pylab as plt  
    x = [1,2,3,3]
    y = map(lambda(x): x * 2, x)
    fig = plt.figure()
    ax = fig.add_axes([0,0,1,1])
    ax.set_title("bleh")
    ax.set_xlabel("xlabel")
    ax.plot(x, y, 'r--')
    fig.savefig("fig.png")
Run Code Online (Sandbox Code Playgroud)

Savefig 没有轴标签的图像

小智 7

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

  • 从实际意义上讲,这个答案是最好的。我*仅*从 png 更改为 jpg,生成的图像包含我期望的轴。今天就够了。但令我沮丧的是,我不明白 **为什么** 这些是不同的,也不明白如何按预期输出 .png。 (2认同)

Mol*_*lly 6

您将轴设置为从图形的左下角开始并填满整个事物。轴标签或标题没有空间。尝试这个:

import matplotlib.pylab as plt  
x = [1,2,3,3]
y = map(lambda(x): x * 2, x)
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.75,0.75]) # axis starts at 0.1, 0.1
ax.set_title("bleh")
ax.set_xlabel("xlabel")
ax.plot(x, y, 'r--')
fig.savefig("fig.png")
Run Code Online (Sandbox Code Playgroud)

带有轴显示的绘图

  • +1 或者只使用 `ax = Fig.add_subplot(1, 1, 1)`,或者更好,只需使用 `fig, ax = plt.subplots()`。 (3认同)
  • 或 `fig, ax = plt.subplots(1, 1, tiny_layout=True)`(假设你的 mpl 版本足够新) (2认同)

Vic*_*GGl 5

我在使用 Jupyter 笔记本和命令:%matplotlib 笔记本时遇到了同样的问题。该图在笔记本中正确显示,但在使用 Fig.savefig() 保存时未打印轴和标题。我将 %matplotlib Notebook 更改为 %matplotlib inline ,这解决了问题。


mou*_*mer 5

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

fig = plt.figure(facecolor=(1, 1, 1))
Run Code Online (Sandbox Code Playgroud)

将背景颜色设置为白色。