matplotlib 3:tight_layout 的 3D 散点图
matplotlib 3: 3D scatter plots with tight_layout
我有一些代码使用 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')
在 matplotlib 2.2.3 中,这使得图形如下:
类似的输出由旧版本生成,至少回到 1.5.1。使用新版本 3.0.0 时,plt.tight_layout()
出现问题,我得到以下输出:
伴随着警告
.../matplotlib/tight_layout.py:177: UserWarning: The left and right margins cannot be made large enough to accommodate all axes decorations
有人可能会争辩说,像这里一样使用不带参数的 tight_layout
无论如何(在较旧的 matplotlib 上)并不会始终如一地导致预期的收紧边距,因此应该避免将 tight_layout
与 3D 一起使用情节摆在首位。但是,通过手动调整 tight_layout
的参数,即使在 3D 绘图上,它(过去)也是一种 trim 边距的好方法。
我猜这是 matplotlib 中的一个错误,但也许他们做了一些我没有注意到的有意更改。任何有关修复的指示都将受到赞赏。
感谢 ImportanceOfBeingErnest 的评论,现在可以使用了:
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)
# The fix
for spine in ax.spines.values():
spine.set_visible(False)
plt.tight_layout()
plt.savefig('scatter.png')
从评论中的链接来看,这似乎会在 matplotlib 3.0.x 中修复。目前,可以使用上面的。
plt.tight_layout()
plt.show()
在你的绘图主体代码下方。
我有一些代码使用 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')
在 matplotlib 2.2.3 中,这使得图形如下:
类似的输出由旧版本生成,至少回到 1.5.1。使用新版本 3.0.0 时,plt.tight_layout()
出现问题,我得到以下输出:
伴随着警告
.../matplotlib/tight_layout.py:177: UserWarning: The left and right margins cannot be made large enough to accommodate all axes decorations
有人可能会争辩说,像这里一样使用不带参数的 tight_layout
无论如何(在较旧的 matplotlib 上)并不会始终如一地导致预期的收紧边距,因此应该避免将 tight_layout
与 3D 一起使用情节摆在首位。但是,通过手动调整 tight_layout
的参数,即使在 3D 绘图上,它(过去)也是一种 trim 边距的好方法。
我猜这是 matplotlib 中的一个错误,但也许他们做了一些我没有注意到的有意更改。任何有关修复的指示都将受到赞赏。
感谢 ImportanceOfBeingErnest 的评论,现在可以使用了:
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)
# The fix
for spine in ax.spines.values():
spine.set_visible(False)
plt.tight_layout()
plt.savefig('scatter.png')
从评论中的链接来看,这似乎会在 matplotlib 3.0.x 中修复。目前,可以使用上面的。
plt.tight_layout()
plt.show()
在你的绘图主体代码下方。