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 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_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_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_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_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_study.graph_objs.Figure or plotly_study.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_study.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_study.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 on page load, if the figure contains frames. Has no effect if the figure does not contain frames. animation_opts (default=None) -- Dict of custom animation parameters that are used for the automatically started animation on page load. This dict is passed to the function plotly_study.animate in plotly_study.js. See https://github.com/plotly/plotly_study.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_study.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_study.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_study.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, )