Matplotlib savefig不保存轴

Matplotlib savefig不保存轴,matplotlib,Matplotlib,我试图保存一个在IPython inline中运行良好的图形,但不将图形保存到包含轴和标题的磁盘 我在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 = fi

我试图保存一个在IPython inline中运行良好的图形,但不将图形保存到包含轴和标题的磁盘

我在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")

您正在将轴设置为从图形的左下角开始,并填充整个图形。没有空间放置轴标签或标题。试试这个:

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")

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

开始时定义
fig=plt.figure(figsize=(15,10))
将文件另存为.jpg并设置
bbox_inches='tight'
-
plt.savefig('filename.jpg',bbox inches='tight',dpi=150)
为我解决了这个问题。
bbox\u inches='tight'
似乎可以解决裁剪问题,但对.png不起作用。

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

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

将背景颜色设置为白色。

+1或者只使用
ax=fig.add_subplot(1,1,1)
,或者更好的是,只使用
fig,ax=plt.subplot()
。或者
fig,ax=plt.subplot(1,1,tight_layout=True)
(假设您的mpl版本足够新)或
plt.figure(tight_layout=True)