在IPython或Jupyter Notebook中显示可旋转的3D图表

83

(Mac OSX 10.10.5)

我可以从matplotlib网站mplot3d复制示例代码,用于绘制3D散点图scatter3d_demo.py,但是图表呈现为静态图像。我无法点击图表并动态旋转以查看3D绘制的数据。

我已经使用示例代码实现了静态3D绘图 - 使用(a)从终端中的ipython,(b)从终端中的ipython笔记本,以及(c)从Anaconda启动器启动的ipython笔记本。

我认为我缺少一些非常基本的步骤,作为假定的知识。

在过去的学习中,绘图已经打开了一个GUI Python应用程序,其中包含一个图形查看器。(下面代码中的解决方案2打开此应用程序。)也许我需要知道将输出图导出到该显示方法的代码? (是的,请使用%matplotlib(仅)作为第一行,不要使用inline或notebook,如下面代码块中的注释所示。)

例如,在ipython笔记本中:

    # These lines are comments
    # Initial setup from an online python notebook tutorial is below. 
    # Note the first line "%matplotlib inline" this is how the tutorial has it.
    # Two solutions 1. use: "%matplotlib notebook" graphs appear dynamic in the notebook.
    #               2. use: "%matplotlib" (only) graphs appear dynamic in separate window. 
    #    ( 2. is the best solution for detailed graphs/plots. )

    %matplotlib inline  
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    pd.set_option('html',False)
    pd.set_option('max_columns',30)
    pd.set_option('max_rows',10)


    # What follows is a copy of the 3D plot example code.
    # Data is randomly generated so there is no external data import.

    def randrange(n, vmin, vmax):
        return (vmax-vmin)*np.random.rand(n) + vmin

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    n = 100
    for c, m, zl, zh in [('r', 'o', -60, -25), ('b', '^', -30, -5)]:
        xs = randrange(n, 23, 50)
        ys = randrange(n, 0, 100)
        zs = randrange(n, zl, zh)
        ax.scatter(xs, ys, zs, c=c, marker=m)

    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

    plt.show()

有人能够确定我缺少什么吗?

查看Python 3.3.6文档,第25.1节,也许是tkinter包...

tkinter包(“Tk界面”)是Tk GUI工具包的标准Python接口。Tk和tkinter都可在大多数Unix平台以及Windows系统上使用。

我认为这与GUI程序的开发有关,所以我不确定这是否相关。(正确,这对解决方案不需要。)


2
尝试添加一个对 ax.mouse_init() 的调用。 - user3419537
在 plt.show() 之前,确定好位置了吗? - Cam_Aust
我不确定它是否重要,但那就是我会放置它的地方。 - user3419537
好的,谢谢。我在这里尝试了一下,但没有成功。我刚刚在我的原始问题中添加了一个可能的新解决方向。 - Cam_Aust
1
@Matt 对这个问题进行了好的整理编辑。谢谢你。我想这应该是我在加入SO后发表的第一篇文章。 - Cam_Aust
显示剩余2条评论
6个回答

160
使用%matplotlib notebook代替%matplotlib inline,即可在IPython笔记本中嵌入交互式图形 - 这需要较新的matplotlib(1.4+)和IPython(3.0+)版本。

是的,就是这样。谢谢jakevdp。对于其他没有使用ipython笔记本并使用在线示例进行学习的人,在将%matplotlib inline更改为%matplotlib notebook后,还要转到菜单“单元格”,并选择“运行所有”。 - Cam_Aust
1
冒昧地在原问题的基础上提问,您知道如何在单独的窗口中打开这样的图形吗?一些具有大量数据的图形需要被放大以便全面检查。能够做到这一点,并使它们具有动态和可旋转性,将是最好的解决方案。这个ipython笔记本环境中是否存在这样的功能? - Cam_Aust
2
如果你只是单独调用%matplotlib,它会使用系统默认的后端(假设在安装时正确配置),并在新窗口中打开图形。 - jakevdp
是的,再次感谢您的帮助。我会更新问题并包含这个解决方案。 - Cam_Aust
FYI,pylab notebook 也可以使用,它等同于 %matplotlib notebookfrom pylab import * - Syrtis Major
3
дёҚжҺЁиҚҗдҪҝз”Ё%pylabгҖӮиҜ·ж”№з”Ё%matplotlibе’ҢжҳҫејҸеҜје…ҘгҖӮ - jakevdp

15

对于 Colab 环境,我发现 HTML() 函数最有用:

enter image description here

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from numpy.random import rand
from IPython.display import HTML
from matplotlib import animation

m = rand(3,3) # m is an array of (x,y,z) coordinate triplets

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for i in range(len(m)): # plot each point + it's index as text above
  x = m[i,0]
  y = m[i,1]
  z = m[i,2]
  label = i
  ax.scatter(x, y, z, color='b')
  ax.text(x, y, z, '%s' % (label), size=20, zorder=1, color='k')

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

def animate(frame):
  ax.view_init(30, frame/4)
  plt.pause(.001)
  return fig

anim = animation.FuncAnimation(fig, animate, frames=200, interval=50)
HTML(anim.to_html5_video())

1
对于Windows(对我来说是Windows 8.1),您可以使用:
%matplotlib inline  
%matplotlib notebook
%pylab

替代方法。

注意:您必须一起执行所有三个命令,否则您将收到内核死亡错误,然后笔记本将自动重启。


1

在你添加之后:

%matplotlib inline  
%matplotlib notebook
%pylab

如果所有的内容仍然是二维的,您可以使用此选项(第二张图片上标记为红色的选项)来拖动和旋转图表,这样您的3D图像就会显示出来:

之前: enter image description here

之后:

enter image description here

我正在使用 Windows 10 和 Jupyter Notebook 6.0.2。


0
对于像我这样甚至更不熟悉的人,快速答案是:
%matplotlib(在上面的导入中)(用于在新窗口中进行交互式图形)
import matplot...等等。
%matplotlib notebook(用于在JupyterNotebook本身内进行图形交互)
import etc...
import etc...

请参见OP问题的顶部。 - Alex

0
在Windows上,我可以通过以下命令启动笔记本,以交互模式显示绘图:
from matplotlib import use
use("Qt5Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
...

如果需要,关闭你的笔记本电脑并重新启动。


这是我在Pycharm上工作的唯一解决方案。谢谢! - Honey Gourami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接