Python 和 Matplotlib:在 Jupyter Notebook 中使 3D 绘图具有交互性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38364435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook
提问by cqcn1991
I use Jupyter Notebook to make analysis of datasets. There are a lot of plots in the notebook, and some of them are 3d plots.
我使用 Jupyter Notebook 来分析数据集。笔记本里有很多图,其中一些是3d图。
I'm wondering if it is possible to make the 3d plot interactive, so I can later play with it in more details?
我想知道是否可以使 3d 绘图具有交互性,以便以后可以更详细地使用它?
Maybe we can add a button on it? Clicking it can pop out a 3d plot and people can zoom, pan, rotate etc.
也许我们可以在上面添加一个按钮?单击它可以弹出一个 3d 绘图,人们可以缩放、平移、旋转等。
My thougths:
我的想法:
1. matplotlib, %qt
1. matplotlib, %qt
This does not fit my case, because I need to continue plot after the 3d plot. %qt
will interfere with later plots.
这不适合我的情况,因为我需要在 3d 绘图之后继续绘图。%qt
会干扰后面的剧情。
2. mpld3
2. mpld3
mpld3
is almost ideal in my case, no need to rewrite anything, compatible with matplotlib. However, it only support 2D plot. And I didn't see any plan working on 3D (https://github.com/mpld3/mpld3/issues/223).
mpld3
在我的情况下几乎是理想的,不需要重写任何东西,与 matplotlib 兼容。但是,它仅支持 2D 绘图。而且我没有看到任何关于 3D 的计划(https://github.com/mpld3/mpld3/issues/223)。
3. bokeh + visjs
3.散景+visjs
Didn't find any actualy example of 3d plot in bokeh
gallery. I only find https://demo.bokeh.org/surface3d, which uses visjs
.
在bokeh
图库中没有找到任何实际的 3d 绘图示例。我只找到https://demo.bokeh.org/surface3d,它使用visjs
.
4. Javascript 3D plot?
4. Javascript 3D 绘图?
Since what I need is just line and surce, is it possible to pass the data to js plot using js in the browser to make it interacive? (Then we may need to add 3d axis as well.) This may be similar to visjs
, and mpld3
.
由于我需要的只是 line 和 surce,是否可以在浏览器中使用 js 将数据传递给 js plot 以使其具有交互性?(然后我们可能还需要添加 3d 轴。)这可能类似于visjs
, 和mpld3
。
回答by eldad-a
try:
尝试:
%matplotlib notebook
%matplotlib notebook
EDIT for JupyterLab users:
为 JupyterLab 用户编辑:
Follow the instructionsto install jupyter-matplotlib
Then the magic command above is no longer needed, as in the example:
然后不再需要上面的魔法命令,如示例所示:
# 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()
Finally, note Maarten Breddels' reply; IMHO ipyvolumeis indeed very impressive (and useful!).
回答by Maarten Breddels
There is a new library called ipyvolumethat may do what you want, the documentation shows live demos. The current version doesn't do meshes and lines, but master from the git repo does (as will version 0.4). (Disclaimer: I'm the author)
有一个名为ipyvolume的新库可以做你想做的事,文档显示了现场演示。当前版本不做网格和线,但来自 git repo 的 master 做(版本 0.4 也是如此)。(免责声明:我是作者)
回答by Oleksii Trekhleb
You may go with Plotlylibrary. It can render interactive 3D plots directly in Jupyter Notebooks.
您可以使用Plotly库。它可以直接在 Jupyter Notebooks 中渲染交互式 3D 图。
To do so you first need to install Plotly by running:
为此,您首先需要通过运行以下命令安装 Plotly:
pip install plotly
You might also want to upgrade the library by running:
您可能还想通过运行以下命令来升级库:
pip install plotly --upgrade
After that in you Jupyter Notebook you may write something like:
之后在你的 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)
As a result the following chart will be plotted for you in Jupyter Notebook and you'll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.
因此,将在 Jupyter Notebook 中为您绘制以下图表,您将能够与其进行交互。当然,您需要提供您的特定数据而不是建议的数据。
回答by geniusupgrader
Plotlyis missing in this list. I've linked the python binding page. It definitively has animated and interative 3D Charts. And since it is Open Source most of that is available offline. Of course it is working with Jupyter
此列表中缺少Plotly。我已经链接了 python 绑定页面。它绝对具有动画和交互式 3D 图表。而且由于它是开源的,因此大部分内容都可以离线使用。当然,它与 Jupyter 一起工作
回答by brm
A solution I came up with is to use a vis.jsinstance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page
我想出的一个解决方案是在 iframe 中使用vis.js实例。这显示了笔记本内的交互式 3D 绘图,该绘图在nbviewer中仍然有效。visjs代码是从3D图表页面的示例代码中借来的
A small notebook to illustrate this: demo
一个小笔记本来说明这一点:演示
The code itself:
代码本身:
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))
回答by Drew
For 3-D visualization pythreejsis the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
对于 3-D 可视化,pythreejs可能是笔记本中最好的方法。它利用笔记本的交互式小部件基础结构,因此 JS 和 python 之间的连接是无缝的。
A more advanced library is bqplotwhich is a d3-based interactive viz library for the iPython notebook, but it only does 2D
一个更高级的库是bqplot,它是一个用于 iPython 笔记本的基于 d3 的交互式可视化库,但它只做 2D