Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5c73f4c

Browse files
committed
added iplot_mpl() and plotly_takeover()
`iplot_mpl()` allows offline matplotlib figure conversion for ipython notebook inline mode. `plotly_takeover()` is a compound command that allows an entire notebook session that was written using matplotlib to use offline plotly without any modification. the later idea was taken from https://github.com/jakevdp/mpld3/blob/202792bcddbfe957ade08a5085691ab176a4563d/mpld3/_display.py#L363
1 parent 20102d6 commit 5c73f4c

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

plotly/offline/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,7 @@
66
from . offline import (
77
download_plotlyjs,
88
init_notebook_mode,
9-
iplot
9+
iplot,
10+
iplot_mpl,
11+
plotly_takeover,
1012
)

plotly/offline/offline.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,19 @@
1616
from plotly.exceptions import PlotlyError
1717

1818

19+
try:
20+
import IPython
21+
_ipython_imported = True
22+
except ImportError:
23+
_ipython_imported = False
24+
25+
try:
26+
import matplotlib
27+
_matplotlib_imported = True
28+
except ImportError:
29+
_matplotlib_imported = False
30+
31+
1932
__PLOTLY_OFFLINE_INITIALIZED = False
2033

2134

@@ -171,6 +184,34 @@ def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
171184
height=height, width=width)))
172185

173186

187+
def iplot_mpl(mpl_fig,mpl_to_plotly_kw={},iplot_kw={}):
188+
'''
189+
Convert a matplotlib figure to plotly dictionary plot inside an
190+
IPython notebook without connecting to an external server.
191+
'''
192+
plotly_plot = tools.mpl_to_plotly(mpl_fig,**mpl_to_plotly_kw)
193+
return iplot(plotly_plot,**iplot_kw)
194+
195+
def plotly_takeover(**kwargs):
196+
'''
197+
Enable the automatic display of figures in the IPython Notebook.
198+
This function should be used with the inline Matplotlib backend
199+
that ships with IPython that can be enabled with `%pylab inline`
200+
or `%matplotlib inline`. This works by adding an HTML formatter
201+
for Figure objects; the existing SVG/PNG formatters will remain
202+
enabled.
203+
204+
(idea taken from `mpld3._display.enable_notebook`)
205+
'''
206+
if __PLOTLY_OFFLINE_INITIALIZED != True:
207+
init_notebook_mode()
208+
ip = IPython.core.getipython.get_ipython()
209+
formatter = ip.display_formatter.formatters['text/html']
210+
formatter.for_type(matplotlib.figure.Figure,
211+
lambda fig, kwds=kwargs: iplot_mpl(fig, **kwds))
212+
213+
214+
174215
def plot():
175216
""" Configured to work with localhost Plotly graph viewer
176217
"""

0 commit comments

Comments
 (0)