Python和Matplotlib:在Jupyter Noteb中使3D plot交互

2024-05-10 05:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Jupyter笔记本对数据集进行分析。笔记本里有很多绘图,有些是3d绘图。

enter image description here

我想知道是否有可能使三维绘图互动,所以我可以稍后玩它在更多的细节?

也许我们可以在上面加个按钮?点击它可以弹出一个三维绘图,人们可以缩放,平移,旋转等


我的想法:

一。matplotlib,%qt

这不适合我的情况,因为我需要在三维打印之后继续打印。%qt将干扰以后的绘图。

2。mpld3

mpld3在我的情况下几乎是理想的,不需要重写任何东西,与matplotlib兼容。但是,它只支持二维打印。我没有看到任何关于3D的计划。

三。bokeh+visjs

bokeh图库中找不到任何实际的三维绘图示例。我只找到https://demo.bokeh.org/surface3d,它使用visjs

四。Javascript三维绘图?

因为我需要的只是line和surce,所以是否可以在浏览器中使用js将数据传递到js plot以使其交互?(然后我们可能还需要添加3d轴。)这可能类似于visjs,和mpld3


Tags: 数据绘图matplotlibjsbokeh情况笔记本jupyter
3条回答

你可以和Plotly图书馆一起去。它可以直接在Jupyter笔记本中渲染交互式3D绘图。

为此,首先需要通过运行以下命令以绘图方式安装:

pip install plotly

您可能还希望通过运行以下命令来升级库:

pip install plotly --upgrade

之后,你可以在笔记本上写下如下内容:

# Import dependencies
import plotly
import plotly.graph_objs as go

# Configure Plotly to be rendered inline in the notebook.
plotly.offline.init_notebook_mode()

# Configure the trace.
trace = go.Scatter3d(
    x=[1, 2, 3],  # <-- Put your data instead
    y=[4, 5, 6],  # <-- Put your data instead
    z=[7, 8, 9],  # <-- Put your data instead
    mode='markers',
    marker={
        'size': 10,
        'opacity': 0.8,
    }
)

# Configure the layout.
layout = go.Layout(
    margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)

data = [trace]

plot_figure = go.Figure(data=data, layout=layout)

# Render the plot.
plotly.offline.iplot(plot_figure)

因此,以下图表将在Jupyter笔记本中为您绘制,您将能够与之交互。当然,你需要提供你的具体数据,而不是建议的数据。

enter image description here

有一个名为ipyvolume的新库可以按您的要求,the documentation shows live demos。当前版本不做网格和线条,但是git repo的master做了(版本0.4也一样)。(免责声明:我是作者)

尝试:

%matplotlib notebook

jakevdp回复 here

为JupyterLab用户编辑:

按照instructions安装jupyter-matplotlib

然后不再需要上面的magic命令,如示例所示:

# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget
# aka import ipympl

import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 2])
plt.show()

最后,请注意Maarten Breddels'reply;IMHOipyvolume确实非常令人印象深刻(而且非常有用!)。

相关问题 更多 >