def _show_(cls, renderer=None, **kwargs): """display figure Parameters ---------- renderer : str names of renderers that control ability for display. If not specified, looks for PLOTLY_RENDERER environment variable, otherwise defaults to 'notebook_connected+plotly_mimetype'. This setting supports display in JupyterLab and Jupyter Notebook, while keeping notebook size small (relies on internet connection for getting the javascript). See help(plotly.io.renderer) for more options. kwargs other arguments for plotly.io.show """ from plotly.io import show if renderer is None and PLOTLY_RENDERER is None: renderer = "notebook_connected+plotly_mimetype" elif renderer is None: renderer = PLOTLY_RENDERER kwargs["renderer"] = renderer drawable = getattr(cls, "drawable", None) or cls fig = getattr(drawable, "figure", None) if fig is None: raise TypeError(f"{cls} does not have a drawable or figure attribute") width = kwargs.get("width", fig.layout.width) height = kwargs.get("height", fig.layout.height) kwargs["width"] = fig.layout.width = width kwargs["height"] = fig.layout.height = height show(fig, **kwargs)
def __init__(self, df, left=False, right=False, min_y=0, max_y=100): # Never pass mutable args! super().__init__(left=False, right=False, min_y=0, max_y=100) # Allows Employee class to pass info # Create interactive graph of cgms # Call graph object figure initialization fig = go.Figure(layout=self.layout) fig.update_layout(xaxis=dict(tickmode="linear", tick0=0, dtick=1)) # Add traces for i in range(len(df.columns) - 1): fig.add_trace( go.Scatter( x=df.iloc[:, 0], y=df.iloc[:, (i + 1)], mode="lines", name=df.columns[(i + 1)], )) pio.show(fig)
def landGrapher(): fig = { "data":[{"type":"bar", 'x':series, 'y':numarr}], } pio.show(fig)
def plot(xp, yp, xn, yn, xa, ya, w): if not disable: x100 = 100 if w[2] == 0: y0 = 0 y100 = 0 else: y0 = -w[0]/w[2] y100 = (-w[0]-100*w[1])/w[2] if y100 > 100: y100 = 100 x100 = (-100*w[2]-w[0])/w[1] fig = { 'data': [{'marker': {'color': '#00ff00', 'symbol': 'circle'}, 'mode': 'markers', 'type': 'scatter', 'x': xp, 'y': yp}, {'marker': {'color': '#ff0000', 'symbol': 'circle'}, 'mode': 'markers', 'type': 'scatter', 'x': xn, 'y': yn}, {'marker': {'color': '#0000ff', 'symbol': 'square-open'}, 'mode': 'markers', 'type': 'scatter', 'x': xa, 'y': ya}, {'type': 'scatter', 'x': [0, x100], 'y': [y0, y100] }] } pio.show(fig)
def plot_plotly(data, layout, pr=""): axis = {"automargin": True} figure = { "data": data, "layout": merge( { "autosize": False, "template": "plotly_white", "xaxis": axis, "yaxis": axis, }, layout, ), } config = { # "editable": True, "displaylogo": False } show(figure, config=config) if pr != "": write_html(figure, "{}.html".format(pr), config=config) write_image(figure, "{}.png".format(pr))
def _ipython_display_(self): import plotly.io as pio if pio.renderers.render_on_display and pio.renderers.default: pio.show(self._fig) else: print(repr(self))
def imshow(df, axes=False, width=800, height=800, tickangle=-60, title=""): try: import plotly.io as pio import plotly.graph_objs as go except: raise ImportError( "Install plotly to use data frame heatmaps: pip install plotly") num_df = numericalize_categorical_variables(df) trace = go.Heatmap(z=num_df.values[::-1, :], hovertemplate="%{text}", text=[[ f"row: {j}<br>col: {col}<br>value: {df.loc[j, col]}" for col in df.columns ] for j in reversed(df.index)], name="") if axes: xaxis = dict(tickmode="array", tickvals=list(range(len(df.columns))), ticktext=list(df.columns), tickangle=tickangle, side="top") yaxis = dict(tickmode="array", tickvals=list(range(len(df))), ticktext=list(reversed(df.index))) else: xaxis = dict(visible=False) yaxis = dict(visible=False) pio.show( go.Figure(trace, layout=dict(width=width, height=height, title=title, xaxis=xaxis, yaxis=yaxis)))
def song_rank_plotly(score, subject): data = [ dict(type='scatter', x=score, y=subject, mode='markers', transforms=[dict( type='groupby', groups=subject, )]) ] layout = dict(title="Rockin' Around The Christmas Tree by Brenda Lee", plot_bgcolor='rgb(255, 255, 255)', yaxis=dict( title="Year", size=5, ), xaxis=dict( title='RANK', gridcolor='rgb(233, 233, 233)', )) fig_dict = dict(data=data, layout=layout) pio.show(fig_dict, validate=False)
def show(self, short: bool = False, keys_limit: int = 10): from arche.report import Report Report.write_summary(self) Report.write_rule_details(self, short=short, keys_limit=keys_limit) for f in self.figures: pio.show(f)
def __init__(self, x_val, y_val, indexes, left=False, right=False, min_y=0, max_y=100): super().__init__(left=False, right=False, min_y=0, max_y=100) # Allows Employee class to pass info self.indexes = indexes # Call graph object figure initialization fig = go.Figure(layout=self.layout) # Add traces fig.add_trace( go.Scatter(x=x_val, y=(y_val), mode='lines', name='baseline corrected ref1')) fig.add_trace( go.Scatter(x=x_val[self.indexes], y=y_val[self.indexes], mode='markers', marker={ 'size': 8, 'color': '#EB55BF' })) pio.show(fig)
def __init__(self, x_val, y_val, base, left=False, right=False, min_y=0, max_y=100): super().__init__(left=False, right=False, min_y=0, max_y=100) # Allows Employee class to pass info self.base = base # Call graph object figure initialization fig = go.Figure(layout=self.layout) # Add traces fig.add_trace( go.Scatter(x=x_val, y=(y_val - self.base), mode='lines', name='baseline corrected ref1')) fig.add_trace( go.Scatter(x=x_val, y=y_val - 8.7, mode='lines', name='ref1')) fig.add_trace( go.Scatter(x=x_val, y=self.base - 8.7, mode='lines', name='baseline')) pio.show(fig)
def plot_fock(state, modes, cutoff=None, renderer="browser"): """Plot the (marginal) Fock state probabilities with Plot.ly. Args: state (:class:`.BaseState`): the state used for plotting modes (list): List of modes to generate output for. If more than one mode is provided, then the reduced state is computed for each mode, and marginal Fock probabilities plotted per mode. cutoff (int): The cutoff value determining the maximum Fock state to get probabilities for. Only required if state is a :class:`~.BaseGaussianState`. renderer (string): the renderer for plotting with Plot.ly """ if cutoff is None: if isinstance(state, BaseGaussianState): raise ValueError(f"No cutoff specified for {state.__class__}.") # BaseFockState has cutoff cutoff = state.cutoff_dim pio = _get_plotly() pio.renderers.default = renderer new_chart = generate_fock_chart(state, modes, cutoff) pio.show(new_chart)
def _ipython_display_(self): import plotly.io as pio if pio.renderers.render_on_display and pio.renderers.default: pio.show(self._fig, config={'displayModeBar': False, 'editable': False}) else: print(repr(self))
def write_details(self, short: bool = False, keys_limit: int = 10) -> None: for result in self.results.values(): if result.detailed_messages_count: self.write_rule_name( f"{result.name} ({result.detailed_messages_count} message(s))" ) self.write_rule_details(result, short, keys_limit) for f in result.figures: pio.show(f)
def test_json_renderer_show_override(fig1): pio.renderers.default = 'notebook' expected_bundle = {'application/json': json.loads( pio.to_json(fig1, remove_uids=False))} with mock.patch('IPython.display.display') as mock_display: pio.show(fig1, renderer='json') mock_display.assert_called_once_with(expected_bundle, raw=True)
def _ipython_display_(self): fig = self.get_figure() is_3d = False # TODO decide by heatmap axis = 'z' if is_3d else 'x' npts = len(fig.get('data')[0][axis]) static_fig = (is_3d and npts > 150) or (not is_3d and npts > 700) renderers = ['jupyterlab'] renderers.append('png' if static_fig else 'my_renderer') pio.renderers.default = '+'.join(renderers) pio.show(fig)
def _ipython_display_(self): fig = self.get_figure() is_3d = False # TODO decide by heatmap axis = 'z' if is_3d else 'x' npts = len(fig.get('data')[0][axis]) static_fig = (is_3d and npts > 150) or (not is_3d and npts > 700) renderers = ['jupyterlab'] renderers.append('png' if static_fig else 'my_renderer') pio.renderers.default = '+'.join(renderers) pio.show(fig, tid=self.tid)
def test_json_renderer_show(fig1): pio.renderers.default = "json" expected_bundle = { "application/json": json.loads(pio.to_json(fig1, remove_uids=False)) } with mock.patch("IPython.display.display") as mock_display: pio.show(fig1) mock_display.assert_called_once_with(expected_bundle, raw=True)
def test_plotly_mimetype_renderer_show(fig1, renderer): pio.renderers.default = renderer expected = {plotly_mimetype: json.loads(pio.to_json(fig1, remove_uids=False))} expected[plotly_mimetype]["config"] = {"plotlyServerURL": "https://plot.ly"} with mock.patch("IPython.display.display") as mock_display: pio.show(fig1) mock_display.assert_called_once_with(expected, raw=True)
def _ipython_display_(self): fig = self.get_figure() is_3d = False # TODO decide by heatmap axis = "z" if is_3d else "x" npts = len(fig.get("data")[0][axis]) static_fig = (is_3d and npts > 150) or (not is_3d and npts > 700) renderers = ["jupyterlab"] renderers.append("png" if static_fig else "my_renderer") pio.renderers.default = "+".join(renderers) pio.show(fig, tid=self.table.tid)
def test_browser_renderer_show(fig1, renderer): pio.renderers.default = renderer renderer_obj = pio.renderers[renderer] using = renderer_obj.using if not isinstance(renderer_obj.using, tuple): using = (using,) # Setup mocks mock_get = MagicMock(name="test get") mock_browser = MagicMock(name="test browser") mock_get.return_value = mock_browser request_responses = [] def perform_request(url): request_responses.append(requests.get(url)) def open_url(url, new=0, autoraise=True): print("open url") # Perform request in thread so that we don't block request_thread = threading.Thread(target=lambda: perform_request(url)) request_thread.daemon = True request_thread.start() mock_browser.open.side_effect = open_url with mock.patch("webbrowser.get", mock_get): pio.show(fig1) # check get args mock_get.assert_any_call(using[0]) # check open args mock_call_args = mock_browser.open.call_args mock_arg1 = mock_call_args[0][0] mock_arg1.startswith("http://127.0.0.1:") mock_kwargs = mock_call_args[1] assert mock_kwargs == dict(new=renderer_obj.new, autoraise=renderer_obj.autoraise) # Give request content a little time to show up tries = 0 while tries < 5 and not request_responses: time.sleep(0.5) # Check request content assert len(request_responses) == 1 response = request_responses[0] assert response.status_code == 200 html = response.content.decode("utf8") assert_full_html(html) assert_offline(html) assert_not_requirejs(html)
def test_plotly_mimetype_renderer_show(fig1, renderer): pio.renderers.default = renderer expected = {plotly_mimetype: json.loads( pio.to_json(fig1, remove_uids=False))} expected[plotly_mimetype]['config'] = { 'plotlyServerURL': 'https://plot.ly'} with mock.patch('IPython.display.display') as mock_display: pio.show(fig1) mock_display.assert_called_once_with(expected, raw=True)
def test_image_renderer(): with mocked_scope() as scope: pio.show(fig, renderer="svg", engine="kaleido", validate=False) renderer = pio.renderers["svg"] scope.transform.assert_called_with( fig, format="svg", width=None, height=None, scale=renderer.scale, )
def test(): t_from = 1632925845 t_to = 1633012738 token_address = '0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6' date_list_pydate = pd.date_range( start=datetime.datetime.fromtimestamp(round(t_from)), end=datetime.datetime.fromtimestamp(round(t_to)), periods=100).to_pydatetime().tolist() date_list_timestamp = [round(x.timestamp()) for x in date_list_pydate] body = ','.join([str(ts) for ts in date_list_timestamp]) url = 'http://78.46.204.87:5001/api/v1/' + 'prices/' + 'polygon' + '?address=' + token_address + '&timeType=timestamp' res = requests.post(url, body).json() pprint(res) t = [(a['ts'], a['price'] / 10**18, a['blockNumb']) for a in res] t = sorted(t, key=lambda tup: tup[0]) import matplotlib.pyplot as plt figlib, ax = plt.subplots() ax.plot([a[0] for a in t], [a[1] for a in t]) plt.show() formatted_res = [(datetime.datetime.fromtimestamp(a['ts']), a['price'] / 10**18) for a in res] d_res = dict(formatted_res) sorted_d_res = collections.OrderedDict(sorted(d_res.items())) pd_dates = pd.to_datetime(list(sorted_d_res.keys())) data = [ dict(type='scatter', x=pd_dates, y=list(sorted_d_res.values()), yaxis='y2', name='OHLC') ] layout = dict() fig = dict(data=data, layout=layout) fig['layout'] = dict() fig['layout']['plot_bgcolor'] = None fig['layout']['template'] = 'plotly_dark' # fig['layout']['plot_bgcolor'] = 'rgb(250, 250, 250)' fig['layout']['autosize'] = False fig['layout']['width'] = 1600 fig['layout']['height'] = 900 fig['layout']['xaxis'] = dict(rangeslider=dict(visible=False)) fig['layout']['yaxis2'] = dict(domain=[0.0, 1], title='blabla' + ' price ($)', side='right') fig['layout']['showlegend'] = False fig['layout']['margin'] = dict(t=15, b=15, r=15, l=15) pio.show(fig) pprint("coucou")
def test_browser_renderer_show(fig1, renderer): pio.renderers.default = renderer renderer_obj = pio.renderers[renderer] # Setup mocks mock_get = MagicMock(name='test get') mock_browser = MagicMock(name='test browser') mock_get.return_value = mock_browser request_responses = [] def perform_request(url): request_responses.append(requests.get(url)) def open_url(url, new=0, autoraise=True): print('open url') # Perform request in thread so that we don't block request_thread = threading.Thread(target=lambda: perform_request(url)) request_thread.daemon = True request_thread.start() mock_browser.open.side_effect = open_url with mock.patch('webbrowser.get', mock_get): pio.show(fig1) # check get args mock_get.assert_called_once_with(renderer_obj.using) # check open args mock_call_args = mock_browser.open.call_args mock_arg1 = mock_call_args[0][0] mock_arg1.startswith('http://127.0.0.1:') mock_kwargs = mock_call_args[1] assert mock_kwargs == dict( new=renderer_obj.new, autoraise=renderer_obj.autoraise) # Give request content a little time to show up tries = 0 while tries < 5 and not request_responses: time.sleep(0.5) # Check request content assert len(request_responses) == 1 response = request_responses[0] assert response.status_code == 200 html = response.content.decode('utf8') assert_full_html(html) assert_offline(html) assert_not_requirejs(html)
def test(self): fig = { "data": [{ "type": "bar", "x": [1, 2, 3], "y": [1, 3, 2] }], "layout": { "title": { "text": "A test graph" } } } pio.show(fig)
def quiver3D(field): x, y, z = np.meshgrid(np.arange(field.shape[0]), np.arange(field.shape[1]), np.arange(field.shape[2])) u = field[:, :, :, 0] v = field[:, :, :, 1] w = field[:, :, :, 2] angle = np.arctan(v / (u + 1e-5)) / np.pi * 2 # u = u*angle # v = v*angle # w = w*angle x, y, z, u, v, w = x.flatten(), y.flatten(), z.flatten(), u.flatten( ), v.flatten(), w.flatten() # pl_deep = [[0.0, 'rgb(39, 26, 44)'], # [0.1, 'rgb(53, 41, 74)'], # [0.2, 'rgb(63, 57, 108)'], # [0.3, 'rgb(64, 77, 139)'], # [0.4, 'rgb(61, 99, 148)'], # [0.5, 'rgb(65, 121, 153)'], # [0.6, 'rgb(72, 142, 157)'], # [0.7, 'rgb(80, 164, 162)'], # [0.8, 'rgb(92, 185, 163)'], # [0.9, 'rgb(121, 206, 162)'], # [1.0, 'rgb(165, 222, 166)']] pl_deep = 'RdBu' trace2 = dict( type='cone', x=x, y=y, z=z, u=u, v=v, w=w, sizemode='absolute', sizeref=0.25, #this is the default value showscale=True, color=angle.flatten(), colorscale=pl_deep, colorbar=dict(thickness=20, ticklen=4), anchor='cm') fig2 = dict(data=[trace2]) title = 'Vertical levels of a numerical weather model' pio.show(fig2, filename='vertical_levels', validate=False)
def show(self, *args, **kwargs) -> None: """Display the figure. Args: *args: Variable length argument list to be passed to ``plotly.io.show()``. **kwargs: Arbitrary keyword arguments to be passed to ``plotly.io.show()``. """ import plotly.io as pio config = {} if 'config' not in kwargs.keys(): config = {'displayModeBar': False, 'editable': False} pio.show(self._fig, *args, config=config, **kwargs)
def plot_train_test(train, test, date_split): data = [ Candlestick(x=train.index, open=train['open'], high=train['high'], low=train['low'], close=train['close'], name='train'), Candlestick(x=test.index, open=test['open'], high=test['high'], low=test['low'], close=test['close'], name='test') ] layout = { 'shapes': [{ 'x0': date_split, 'x1': date_split, 'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper', 'line': { 'color': 'rgb(0,0,0)', 'width': 1 } }], 'annotations': [{ 'x': date_split, 'y': 1.0, 'xref': 'x', 'yref': 'paper', 'showarrow': False, 'xanchor': 'left', 'text': ' test data' }, { 'x': date_split, 'y': 1.0, 'xref': 'x', 'yref': 'paper', 'showarrow': False, 'xanchor': 'right', 'text': 'train data ' }] } figure = Figure(data=data, layout=layout) pio.show(figure)
def chart_na_values(df: pd.DataFrame, label) -> None: null_feat = pd.DataFrame(df[f'{label}'].size - df.isnull().sum(), columns=['Count']) null_feat.index = null_feat.index.str.replace('_', ' ').str.title() trace = go.Bar(x=null_feat.index, y=null_feat['Count'], opacity=0.8, marker=dict(color='lightgrey', line=dict(color='#000000', width=1.5))) layout = dict(title={'text': "Missing Values"}) fig = dict(data=[trace], layout=layout) pio.show(fig) return None
def plot_loss_reward(total_losses, total_rewards): figure = tools.make_subplots(rows=1, cols=2, subplot_titles=('loss', 'reward'), print_grid=False) figure.append_trace( Scatter(y=total_losses, mode='lines', line=dict(color='skyblue')), 1, 1) figure.append_trace( Scatter(y=total_rewards, mode='lines', line=dict(color='orange')), 1, 2) figure['layout']['xaxis1'].update(title='epoch') figure['layout']['xaxis2'].update(title='epoch') figure['layout'].update(height=400, width=900, showlegend=False) pio.show(figure)
def plot_quad(state, modes, xvec, pvec, renderer="browser"): """Plot the x and p-quadrature probability distributions with Plot.ly. Args: state (:class:`.BaseState`): the state used for plotting mode (int): mode used to calculate the reduced Wigner function xvec (array): array of discretized :math:`x` quadrature values pvec (array): array of discretized :math:`p` quadrature values renderer (string): the renderer for plotting with Plot.ly """ pio = _get_plotly() pio.renderers.default = renderer for mode in modes: new_chart = generate_quad_chart(state, mode, xvec, pvec) pio.show(new_chart)
def plot_wigner(state, mode, xvec, pvec, renderer="browser", contours=True): """Plot the Wigner function with Plot.ly. Args: state (:class:`.BaseState`): the state used for plotting mode (int): mode used to calculate the reduced Wigner function xvec (array): array of discretized :math:`x` quadrature values pvec (array): array of discretized :math:`p` quadrature values renderer (string): the renderer for plotting with Plot.ly contours (bool): whether to show the contour lines in the plot """ pio = _get_plotly() pio.renderers.default = renderer data = state.wigner(mode, xvec, pvec) new_chart = generate_wigner_chart(data, xvec, pvec, contours=contours) pio.show(new_chart)
def test_pdf_renderer_show_override(fig1): pio.renderers.default = None # Configure renderer so that we can use the same parameters # to build expected image below pio.renderers['png'].width = 400 pio.renderers['png'].height = 500 pio.renderers['png'].scale = 1 image_bytes_png = pio.to_image( fig1, format='png', width=400, height=500, scale=1) image_str_png = base64.b64encode(image_bytes_png).decode('utf8') with mock.patch('IPython.display.display') as mock_display: pio.show(fig1, renderer='png') expected_bundle = {'image/png': image_str_png} mock_display.assert_called_once_with(expected_bundle, raw=True)
def test_colab_renderer_show(fig1): pio.renderers.default = 'colab' with mock.patch('IPython.display.display') as mock_display: pio.show(fig1) # Get display call arguments mock_call_args = mock_display.call_args mock_arg1 = mock_call_args[0][0] # Check for html bundle assert list(mock_arg1) == ['text/html'] # Check html contents html = mock_arg1['text/html'] assert_full_html(html) assert_connected(html) assert_not_requirejs(html) # check kwargs mock_kwargs = mock_call_args[1] assert mock_kwargs == {'raw': True}
def test_notebook_connected_show(fig1, name, connected): # Set renderer pio.renderers.default = name # Show with mock.patch('IPython.display.display_html') as mock_display_html: with mock.patch('IPython.display.display') as mock_display: pio.show(fig1) # ### Check initialization ### # Get display call arguments mock_call_args_html = mock_display_html.call_args mock_arg1_html = mock_call_args_html[0][0] # Check init display contents bundle_display_html = mock_arg1_html if connected: assert_connected(bundle_display_html) else: assert_offline(bundle_display_html) # ### Check display call ### # Get display call arguments mock_call_args = mock_display.call_args mock_arg1 = mock_call_args[0][0] # Check for html bundle assert list(mock_arg1) == ['text/html'] # Check html display contents bundle_html = mock_arg1['text/html'] assert_not_full_html(bundle_html) assert_requirejs(bundle_html) # check kwargs mock_kwargs = mock_call_args[1] assert mock_kwargs == {'raw': True}
def test_svg_renderer_show(fig1): pio.renderers.default = 'svg' pio.renderers['svg'].width = 400 pio.renderers['svg'].height = 500 pio.renderers['svg'].scale = 1 with mock.patch('IPython.display.display') as mock_display: pio.show(fig1) # Check call args. # SVGs generated by orca are currently not reproducible so we just # check the mime type and that the resulting string is an SVG with the # expected size mock_call_args = mock_display.call_args mock_arg1 = mock_call_args[0][0] assert list(mock_arg1) == ['image/svg+xml'] assert mock_arg1['image/svg+xml'].startswith( '<svg class="main-svg" xmlns="http://www.w3.org/2000/svg" ' 'xmlns:xlink="http://www.w3.org/1999/xlink" ' 'width="400" height="500"') mock_kwargs = mock_call_args[1] assert mock_kwargs == {'raw': True}
def iplot(figure_or_data, show_link=False, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600, config=None, auto_play=True, animation_opts=None): """ Draw plotly graphs inside an IPython or Jupyter notebook figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=False) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets the format of the image to be downloaded, if we choose to download an image. This parameter has a default value of None indicating that no image should be downloaded. Please note: for higher resolution images and more export options, consider using plotly.io.write_image. See https://plot.ly/python/static-image-export/ for more details. filename (default='plot') -- Sets the name of the file your image will be saved to. The extension should not be included. image_height (default=600) -- Specifies the height of the image in `px`. image_width (default=800) -- Specifies the width of the image in `px`. config (default=None) -- Plot view options dictionary. Keyword arguments `show_link` and `link_text` set the associated options in this dictionary if it doesn't contain them already. auto_play (default=True) -- Whether to automatically start the animation sequence if the figure contains frames. Has no effect if the figure does not contain frames. animation_opts (default=None) -- dict of custom animation parameters to be passed to the function Plotly.animate in Plotly.js. See https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js for available options. Has no effect if the figure does not contain frames, or auto_play is False. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` animation_opts Example: ``` from plotly.offline import iplot figure = {'data': [{'x': [0, 1], 'y': [0, 1]}], 'layout': {'xaxis': {'range': [0, 5], 'autorange': False}, 'yaxis': {'range': [0, 5], 'autorange': False}, 'title': 'Start Title'}, 'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]}, {'data': [{'x': [1, 4], 'y': [1, 4]}]}, {'data': [{'x': [3, 4], 'y': [3, 4]}], 'layout': {'title': 'End Title'}}]} iplot(figure,animation_opts="{frame: {duration: 1}}") ``` """ import plotly.io as pio ipython = get_module('IPython') if not ipython: raise ImportError('`iplot` can only run inside an IPython Notebook.') config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) # Get figure figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) # Handle image request post_script = build_save_image_post_script( image, filename, image_height, image_width, 'iplot') # Show figure pio.show(figure, validate=validate, config=config, auto_play=auto_play, post_script=post_script, animation_opts=animation_opts)