从终端运行时,绘图是空白图像,从 jupyter 运行

问题描述 投票:0回答:1

我需要显示点云,我正在使用带有 Axes3D 和散点图的 matplotlib 图。

这是玩具代码:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

xs = np.arange(10)
ys = np.arange(10)
zs = np.arange(10)

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter(xs, ys, zs, color='green')
    
# setting title and labels
ax.set_title("3D plot")
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
ax.autoscale()
# displaying the plot
#plt.savefig("test")
plt.show()
#fig.savefig("test.png")

如果由终端运行,同样的代码会产生一个空图像,如果在 jupyter 单元格中运行,这(如预期的那样) expexted result, obtained in jupyter

edit:我尝试运行 Wayne 发布的解决方案并得到这个:https://i.stack.imgur.com/8jPM4.png 从 VSCode 终端运行程序时,它在绘图窗口中打开

python matplotlib scatter-plot
1个回答
0
投票

试试你的代码的这个变体:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
 
xs = np.arange(10)
ys = np.arange(10)
zs = np.arange(10)


# plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xs, ys, zs, color='green')
ax.set_title("3D plot")
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
#ax.view_init(50, 185)
plt.show()

当您转到here并单击“

launch binder
”时,我根据可用笔记本下列出的第一个笔记本中的第一个情节改编了它。 (我也在下一段的最后一句中链接到笔记本的静态版本。)

重要的是,它在从 here 在线启动的 Spyder 会话中工作,我看到您的代码无法在“绘图选项卡”中显示绘图。我认为这是因为它使用的是旧代码方法,并且正如我的评论使我相信使用

projection='3d'
更多是当前的方法。示例是 here,建议解决
Axes3D(fig)
的弃用问题。 (当我在 Jupyter 中运行您的代码时以及在从 here 启动的会话中在终端中将您的代码作为脚本运行时出现弃用警告。)如上所述,示例代码我的建议基于 here,我从 Yan Holtz 的 Python Graph Gallery 获得的表格,也适用于 Spyder 和 Jupyter,没有任何弃用警告。

我建议的代码变体也可以在 Jupyter 中运行。没有任何弃用警告。

为什么在使用

Axes3D(fig)
时 Spyder 的“绘图”选项卡中没有显示绘图,并且没有显示任何错误或弃用警告,这超出了我的理解范围。但我怀疑就像你报告的那样。某种指标会很好。

© www.soinside.com 2019 - 2024. All rights reserved.