【问题标题】:matplotlib 3: 3D scatter plots with tight_layoutmatplotlib 3:带有tight_layout 的3D 散点图
【发布时间】:2018-09-24 21:08:05
【问题描述】:

我有一些代码使用 matplotlib 的 scattertight_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: 左右边距不能足够大以容纳所有轴装饰

有人可能会争辩说,使用tight_layout 没有参数,因为这里不会(在旧的matplotlibs 上)始终导致预期的紧缩边距,因此首先应该避免将tight_layout 与3D 图一起使用。但是,通过手动调整 tight_layout 的参数,即使在 3D 绘图上,它也是(过去是)一种不错的修剪边距的方法。

我的猜测是这是 matplotlib 中的一个错误,但也许他们做了一些我没有注意到的故意改变。任何有关修复的指针表示赞赏。

【问题讨论】:

  • 它可能不起作用,但可能的解决方法是显式设置图形的大小而不是使用tight_layout,例如 plt.figure(figsize=(20,10))
  • 设置figsize 不等同于tight_layout。另外,我已经在我的实际代码中设置了figsize,因为我关心最终图像的确切像素大小。
  • This is the issuethis is the fix。我想您可以手动应用它,即在调用 tight_layout 之前使刺不可见。

标签: python python-3.x matplotlib scatter-plot


【解决方案1】:

感谢 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 中修复。目前,可以使用上述方法。

【讨论】:

  • 我遇到了类似的问题,但在我的情况下,它仍然无法在不再需要修复的 3.0.1 中工作。事实证明,matplotlib 中似乎还有另一个错误(now reported):如果在调用之前添加文本到 3d-axes 会破坏紧密布局()。将此作为一个已知的工作示例有助于弄清楚它,所以谢谢!
【解决方案2】:
plt.tight_layout()
plt.show()

就在您的主要绘图代码下方。

【讨论】:

    猜你喜欢
    • 2016-12-30
    • 2012-02-12
    • 2011-07-26
    • 1970-01-01
    • 2015-10-18
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多