【发布时间】:2018-09-24 21:08:05
【问题描述】:
我有一些代码使用 matplotlib 的 scatter 和 tight_layout 生成 3D 散点图,请参见下面的简化代码:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import proj3d
fig = plt.figure()
ax = fig.gca(projection='3d')
N = 100
x = np.random.random(N)
y = np.random.random(N)
z = np.random.random(N)
ax.scatter(x, y, z)
plt.tight_layout() # <-- Without this, everything is fine
plt.savefig('scatter.png')
类似的输出由旧版本生成,至少回到 1.5.1。使用新版本 3.0.0 时,plt.tight_layout() 出现问题,我得到以下输出:
随之而来的是警告
.../matplotlib/tight_layout.py:177: UserWarning: 左右边距不能足够大以容纳所有轴装饰
有人可能会争辩说,使用tight_layout 没有参数,因为这里不会(在旧的matplotlibs 上)始终导致预期的紧缩边距,因此首先应该避免将tight_layout 与3D 图一起使用。但是,通过手动调整 tight_layout 的参数,即使在 3D 绘图上,它也是(过去是)一种不错的修剪边距的方法。
我的猜测是这是 matplotlib 中的一个错误,但也许他们做了一些我没有注意到的故意改变。任何有关修复的指针表示赞赏。
【问题讨论】:
-
它可能不起作用,但可能的解决方法是显式设置图形的大小而不是使用tight_layout,例如 plt.figure(figsize=(20,10))
-
设置
figsize不等同于tight_layout。另外,我已经在我的实际代码中设置了figsize,因为我关心最终图像的确切像素大小。 -
This is the issue 和 this is the fix。我想您可以手动应用它,即在调用
tight_layout之前使刺不可见。
标签: python python-3.x matplotlib scatter-plot