Python和Matplotlib:在Jupyter Notebook中实现3D绘图交互

2ledvvac  于 2023-04-21  发布在  Python
关注(0)|答案(7)|浏览(341)

我使用Jupyter Notebook对数据集进行分析。Notebook中有很多图,其中一些是3D图。

我想知道是否有可能使3d情节互动,所以我可以稍后玩它在更多的细节?
也许我们可以在上面加一个按钮?点击它可以弹出一个3d图,人们可以缩放,平移,旋转等。
我的想法:

1. matplotlib,%qt

这不适合我的情况,因为我需要在3D绘图后继续绘图。%qt会干扰后面的绘图。

2. mpld3

mpld3在我的情况下几乎是理想的,不需要重写任何东西,与matplotlib兼容。然而,它只支持2D绘图。我没有看到任何计划在3D上工作(https://github.com/mpld3/mpld3/issues/223)。

3.散景+ visjs

bokeh gallery中没有找到任何3d绘图的实际示例。我只找到了https://demo.bokeh.org/surface3d,它使用了visjs

4. Javascript 3D plot?

由于我需要的只是线和表面,是否可以在浏览器中使用js将数据传递到js plot以使其具有交互性?(然后我们可能还需要添加3d轴。)这可能类似于visjsmpld3

c6ubokkw

c6ubokkw1#

尝试:
%matplotlib notebook
参见jakevdp回复here

JupyterLab用户编辑:

按照说明安装jupyter-matplotlib
那么就不再需要上面的魔法命令了,如下面的例子所示:

# 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;IMHO ipyvolume确实非常令人印象深刻(而且很有用!)。

yshpjwxd

yshpjwxd2#

你可以使用Plotly库。它可以直接在Jupyter Notebooks中渲染交互式3D绘图。
为此,您首先需要通过运行以下命令来安装Plotly:

pip install plotly

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

pip install plotly --upgrade

之后,在Jupyter Notebook中,您可以编写如下内容:

# 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 Notebook中为您绘制,您将能够与它进行交互。当然,您需要提供特定的数据而不是建议的数据。

pnwntuvh

pnwntuvh3#

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

hmae6n7t

hmae6n7t4#

Plotly在这个列表中丢失。我已经链接了python绑定页面。它肯定有动画和交互式3D图表。由于它是开源的,大部分都可以离线使用。当然,它可以与Jupyter一起使用

tjjdgumg

tjjdgumg5#

我想到的一个解决方案是在iframe中使用vis.js示例。这在笔记本中显示了一个交互式3D绘图,它仍然可以在nbviewer中工作。visjs代码是从3D图形page上的示例代码中借用的
一个小笔记本来说明这一点:demo
代码本身:

from IPython.core.display import display, HTML
import json

def plot3D(X, Y, Z, height=600, xlabel = "X", ylabel = "Y", zlabel = "Z", initialCamera = None):

    options = {
        "width": "100%",
        "style": "surface",
        "showPerspective": True,
        "showGrid": True,
        "showShadow": False,
        "keepAspectRatio": True,
        "height": str(height) + "px"
    }

    if initialCamera:
        options["cameraPosition"] = initialCamera

    data = [ {"x": X[y,x], "y": Y[y,x], "z": Z[y,x]} for y in range(X.shape[0]) for x in range(X.shape[1]) ]
    visCode = r"""
       <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" type="text/css" rel="stylesheet" />
       <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
       <div id="pos" style="top:0px;left:0px;position:absolute;"></div>
       <div id="visualization"></div>
       <script type="text/javascript">
        var data = new vis.DataSet();
        data.add(""" + json.dumps(data) + """);
        var options = """ + json.dumps(options) + """;
        var container = document.getElementById("visualization");
        var graph3d = new vis.Graph3d(container, data, options);
        graph3d.on("cameraPositionChange", function(evt)
        {
            elem = document.getElementById("pos");
            elem.innerHTML = "H: " + evt.horizontal + "<br>V: " + evt.vertical + "<br>D: " + evt.distance;
        });
       </script>
    """
    htmlCode = "<iframe srcdoc='"+visCode+"' width='100%' height='" + str(height) + "px' style='border:0;' scrolling='no'> </iframe>"
    display(HTML(htmlCode))
3phpmpom

3phpmpom6#

对于3D可视化,pythreejs可能是笔记本中最好的方式。它利用了笔记本的交互式小部件基础设施,因此JS和python之间的连接是无缝的。
一个更高级的库是bqplot,它是一个基于d3的交互式viz库,用于iPython notebook,但它只支持2D

lhcgjxsq

lhcgjxsq7#

plotly的px.scatter_3d是最简单的解决方案,我发现3d绘图动画后,尝试与matplotlib没有运气-你可以在这篇文章中找到一个很好的例子:Why does the size of my 3D Plotly Scatterplot randomly change?

相关问题