From 5c73f4c4838669c091c41659d79f9582730a3e87 Mon Sep 17 00:00:00 2001 From: arsenovic Date: Thu, 3 Dec 2015 14:55:34 -0500 Subject: [PATCH] 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 --- plotly/offline/__init__.py | 4 +++- plotly/offline/offline.py | 41 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/plotly/offline/__init__.py b/plotly/offline/__init__.py index df04b62cc01..416105dab7e 100644 --- a/plotly/offline/__init__.py +++ b/plotly/offline/__init__.py @@ -6,5 +6,7 @@ from . offline import ( download_plotlyjs, init_notebook_mode, - iplot + iplot, + iplot_mpl, + plotly_takeover, ) diff --git a/plotly/offline/offline.py b/plotly/offline/offline.py index cb9e3762bed..44cecd347f7 100644 --- a/plotly/offline/offline.py +++ b/plotly/offline/offline.py @@ -16,6 +16,19 @@ from plotly.exceptions import PlotlyError +try: + import IPython + _ipython_imported = True +except ImportError: + _ipython_imported = False + +try: + import matplotlib + _matplotlib_imported = True +except ImportError: + _matplotlib_imported = False + + __PLOTLY_OFFLINE_INITIALIZED = False @@ -171,6 +184,34 @@ def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', height=height, width=width))) +def iplot_mpl(mpl_fig,mpl_to_plotly_kw={},iplot_kw={}): + ''' + Convert a matplotlib figure to plotly dictionary plot inside an + IPython notebook without connecting to an external server. + ''' + plotly_plot = tools.mpl_to_plotly(mpl_fig,**mpl_to_plotly_kw) + return iplot(plotly_plot,**iplot_kw) + +def plotly_takeover(**kwargs): + ''' + Enable the automatic display of figures in the IPython Notebook. + This function should be used with the inline Matplotlib backend + that ships with IPython that can be enabled with `%pylab inline` + or `%matplotlib inline`. This works by adding an HTML formatter + for Figure objects; the existing SVG/PNG formatters will remain + enabled. + + (idea taken from `mpld3._display.enable_notebook`) + ''' + if __PLOTLY_OFFLINE_INITIALIZED != True: + init_notebook_mode() + ip = IPython.core.getipython.get_ipython() + formatter = ip.display_formatter.formatters['text/html'] + formatter.for_type(matplotlib.figure.Figure, + lambda fig, kwds=kwargs: iplot_mpl(fig, **kwds)) + + + def plot(): """ Configured to work with localhost Plotly graph viewer """