问题:如何在IPython Notebook中打开交互式matplotlib窗口?

我正在使用IPython,--pylab=inline有时想快速切换到交互式可缩放的matplotlib GUI来查看图(在终端Python控制台中绘制图时会弹出的图)。我该怎么办?最好不要离开或重新启动笔记本。

IPy笔记本中的内联绘图的问题在于它们的分辨率有限,我无法放大以查看一些较小的部分。使用从终端启动的maptlotlib GUI,我可以选择要放大的图形矩形,并相应地调整轴。我尝试过

from matplotlib import interactive
interactive(True)

interactive(False)

但这什么也没做。我在网上也找不到任何提示。

I am using IPython with --pylab=inline and would sometimes like to quickly switch to the interactive, zoomable matplotlib GUI for viewing plots (the one that pops up when you plot something in a terminal Python console). How could I do that? Preferably without leaving or restarting my notebook.

The problem with inline plots in IPy notebook is that they are of a limited resolution and I can’t zoom into them to see some smaller parts. With the maptlotlib GUI that starts from a terminal, I can select a rectangle of the graph that I want to zoom into and the axes adjust accordingly. I tried experimenting with

from matplotlib import interactive
interactive(True)

and

interactive(False)

but that didn’t do anything. I couldn’t find any hint online either.


回答 0

根据文档,您应该能够像这样来回切换:

In [2]: %matplotlib inline 
In [3]: plot(...)

In [4]: %matplotlib qt  # wx, gtk, osx, tk, empty uses default
In [5]: plot(...) 

然后会弹出一个常规绘图窗口(可能需要在笔记本计算机上重新启动)。

我希望这有帮助。

According to the documentation, you should be able to switch back and forth like this:

In [2]: %matplotlib inline 
In [3]: plot(...)

In [4]: %matplotlib qt  # wx, gtk, osx, tk, empty uses default
In [5]: plot(...) 

and that will pop up a regular plot window (a restart on the notebook may be necessary).

I hope this helps.


回答 1

如果您要做的只是从内联图切换到交互式图,然后再切换回去(以便可以平移/缩放),则最好使用%matplotlib magic。

#interactive plotting in separate window
%matplotlib qt 

然后返回html

#normal charts inside notebooks
%matplotlib inline 

%pylab magic会导入很多其他内容,甚至可能导致冲突。它执行“从pylab导入*”。

您还可以使用新的笔记本后端(在matplotlib 1.4中添加):

#interactive charts inside notebooks, matplotlib 1.4+
%matplotlib notebook 

如果您想在图表中增加交互性,可以查看mpld3bokeh。mpld3很棒,如果您没有大量数据点(例如<5k +),并且您想要使用普通的matplotlib语法,但与%matplotlib notebook相比,则具有更多的交互性。Bokeh可以处理大量数据,但是您需要学习它的语法,因为它是一个单独的库。

你也可以签出pivottablejs(pip installivottablejs)

from pivottablejs import pivot_ui
pivot_ui(df)

不管是多么酷的交互式数据探索,它都完全会破坏可重复性。它发生在我身上,所以一旦我感觉到数据,我就尝试只在早期就使用它,并切换到纯内联matplotlib / seaborn。

If all you want to do is to switch from inline plots to interactive and back (so that you can pan/zoom), it is better to use %matplotlib magic.

#interactive plotting in separate window
%matplotlib qt 

and back to html

#normal charts inside notebooks
%matplotlib inline 

%pylab magic imports a bunch of other things and may even result in a conflict. It does “from pylab import *”.

You also can use new notebook backend (added in matplotlib 1.4):

#interactive charts inside notebooks, matplotlib 1.4+
%matplotlib notebook 

If you want to have more interactivity in your charts, you can look at mpld3 and bokeh. mpld3 is great, if you don’t have ton’s of data points (e.g. <5k+) and you want to use normal matplotlib syntax, but more interactivity, compared to %matplotlib notebook . Bokeh can handle lots of data, but you need to learn it’s syntax as it is a separate library.

Also you can check out pivottablejs (pip install pivottablejs)

from pivottablejs import pivot_ui
pivot_ui(df)

However cool interactive data exploration is, it can totally mess with reproducibility. It has happened to me, so I try to use it only at the very early stage and switch to pure inline matplotlib/seaborn, once I got the feel for the data.


回答 2

从matplotlib 1.4.0开始,现在有一个用于笔记本的交互式后端

%matplotlib notebook

有一些版本的IPython尚未注册该别名,回退是:

%matplotlib nbagg

如果那不起作用,请更新您的IPython。

要玩这个游戏,请转到tmpnb.org

并粘贴

%matplotlib notebook

import pandas as pd
import numpy as np
import matplotlib

from matplotlib import pyplot as plt
import seaborn as sns

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
                  columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot(); plt.legend(loc='best')    

进入代码单元(或仅修改现有的python演示笔记本)

Starting with matplotlib 1.4.0 there is now an an interactive backend for use in the notebook

%matplotlib notebook

There are a few version of IPython which do not have that alias registered, the fall back is:

%matplotlib nbagg

If that does not work update you IPython.

To play with this, goto tmpnb.org

and paste

%matplotlib notebook

import pandas as pd
import numpy as np
import matplotlib

from matplotlib import pyplot as plt
import seaborn as sns

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
                  columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot(); plt.legend(loc='best')    

into a code cell (or just modify the existing python demo notebook)


回答 3

更好的解决方案可能是图表库。它使您能够使用出色的Highcharts javascript库制作精美的交互式绘图。Highcharts使用HTMLsvg标记,因此您的所有图表实际上都是矢量图像。

一些功能:

  • 您可以下载.png,.jpg和.svg格式的矢量图,因此永远不会遇到分辨率问题
  • 交互式图表(缩放,滑动,将鼠标悬停在点上,…)
  • 在IPython笔记本中可用
  • 使用异步绘图功能可同时探索数百个数据结构。

免责声明:我是图书馆的开发人员

A better solution for your problem might be the Charts library. It enables you to use the excellent Highcharts javascript library to make beautiful and interactive plots. Highcharts uses the HTML svg tag so all your charts are actually vector images.

Some features:

  • Vector plots which you can download in .png, .jpg and .svg formats so you will never run into resolution problems
  • Interactive charts (zoom, slide, hover over points, …)
  • Usable in an IPython notebook
  • Explore hundreds of data structures at the same time using the asynchronous plotting capabilities.

Disclaimer: I’m the developer of the library


回答 4

我在2011年5月28日从www.continuum.io/downloads的Anaconda的“ jupyter QTConsole”中使用ipython。

这是一个使用ipython magic在一个单独的窗口和一个内联绘图模式之间来回切换的示例。

>>> import matplotlib.pyplot as plt

# data to plot
>>> x1 = [x for x in range(20)]

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Note: the %matplotlib magic above causes:
#      plt.plot(...) 
# to implicitly include a:
#      plt.show()
# after the command.
#
# (Not sure how to turn off this behavior
# so that it matches behavior without using %matplotlib magic...)
# but its ok for interactive work...

I’m using ipython in “jupyter QTConsole” from Anaconda at www.continuum.io/downloads on 5/28/20117.

Here’s an example to flip back and forth between a separate window and an inline plot mode using ipython magic.

>>> import matplotlib.pyplot as plt

# data to plot
>>> x1 = [x for x in range(20)]

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Note: the %matplotlib magic above causes:
#      plt.plot(...) 
# to implicitly include a:
#      plt.show()
# after the command.
#
# (Not sure how to turn off this behavior
# so that it matches behavior without using %matplotlib magic...)
# but its ok for interactive work...

回答 5

重新启动内核并清除输出(如果不是从新笔记本开始),然后运行

%matplotlib tk

有关更多信息,请转到使用matplotlib进行绘图

Restart kernel and clear output (if not starting with new notebook), then run

%matplotlib tk

For more info go to Plotting with matplotlib


回答 6

您可以使用

%matplotlib qt

如果出现错误,ImportError: Failed to import any qt binding则将PyQt5安装为:pip install PyQt5它对我有用。

You can use

%matplotlib qt

If you got the error ImportError: Failed to import any qt binding then install PyQt5 as: pip install PyQt5 and it works for me.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。