diff --git a/doc/python/creating-and-updating-figures.md b/doc/python/creating-and-updating-figures.md index 7e7502fa850..005dd6704a7 100644 --- a/doc/python/creating-and-updating-figures.md +++ b/doc/python/creating-and-updating-figures.md @@ -5,8 +5,8 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: "1.1" - jupytext_version: 1.1.1 + format_version: '1.2' + jupytext_version: 1.3.2 kernelspec: display_name: Python 3 language: python @@ -20,114 +20,162 @@ jupyter: name: python nbconvert_exporter: python pygments_lexer: ipython3 - version: 3.7.3 + version: 3.7.0 plotly: - description: Creating and Updating Figures from Python + description: Creating and Updating Figures with Plotly's Python graphing library display_as: file_settings language: python layout: base name: Creating and Updating Figures + order: 2 page_type: example_index permalink: python/creating-and-updating-figures/ redirect_from: - - python/user-guide/ - - python/user-g/ + - python/user-guide/ + - python/user-g/ thumbnail: thumbnail/creating-and-updating-figures.png v4upgrade: true - order: 2 --- ### Representing Figures -#### Figures as dictionaries +The goal of the plotly.py package is to provide a pleasant Python interface for creating figure specifications which are displayed by the [plotly.js](https://plot.ly/javascript) JavaScript graphing library. + +In the context of the plotly.js library, a figure is specified by a declarative [JSON](https://www.json.org/json-en.html) data structure. -The goal of plotly.py is to provide a pleasant Python interface for creating figure specifications for display in the Plotly.js JavaScript library. In Plotly.js, a figure is specified by a declarative JSON data structure, and so the ultimate responsibility of plotly.py is to produce Python dictionaries that can be serialized into a JSON data structure that represents a valid figure. +Therefore, you should always keep in mind as you are creating and updating figures using the plotly.py package that its ultimate goal is to help users produce Python [dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) that can be automatically [serialized](https://en.wikipedia.org/wiki/Serialization) into the JSON data structure that the plotly.js graphing library understands. -As a concrete example, here is a Python dictionary that represents a figure containing a single bar trace and a title. +#### Figures As Dictionaries + +The `fig` dictonary in the example below describes a figure. It contains a single `bar` trace and a title. ```python -fig = { +fig = dict({ "data": [{"type": "bar", "x": [1, 2, 3], "y": [1, 3, 2]}], - "layout": {"title": {"text": "A Bar Chart"}} -} + "layout": {"title": {"text": "A Figure Specified By Python Dictionary"}} +}) # To display the figure defined by this dict, use the low-level plotly.io.show function import plotly.io as pio + pio.show(fig) ``` -The value of the top-level `"data"` key is a list of trace specifications. Each trace specification has a special `"type"` key that indicates the trace type that is being defined (e.g. a `"bar"`, `"scatter"`, `"contour"`, etc.). The rest of the keys in the trace specification are used to configure the properties of the trace of this type. +Let's take a closer look at structure of the `fig` dictionary in order to better understand how `plotly.py` figures are built. + +##### The `"data"` Key + +The `"data"` key stores the value of list which describes the trace or traces which make up a figure. It is still a list even if the figure only contains one trace, as in the example above. + +Each trace in the list stored by the `"data"` key is itself defined by a dictionary. The type of the trace (`"bar"`, `"scatter"`, `"contour"`, etc...) is specified with a `"type"` key, and the rest of the keys in a trace specification dictionary (`x`, `y`, etc...) are used to define the properties specific to the trace of that type. + +##### The `"layout"` Key + +The`"layout"` key stores a dictionary that specifies properties related to customizing how the figure looks, such as its title, typography, margins, axes, annotations, shapes, legend and more. In contrast to trace configuration options, which apply only to individual traces, layout configuration options apply to the figure as a whole. + +The [_Full Reference_](https://plot.ly/python/reference/) page contains descriptions of all of the supported trace and layout attributes and configuration options. -The value of the top-level `"layout"` key is a dictionary that specifies the properties of the figure's layout. In contrast to trace configuration options that apply to individual traces, the layout configuration options apply to the figure as a whole, customizing items like the axes, annotations, shapes, legend, and more. +If working from the _Full Reference_ to build figures as Python dictionaries and lists suites your needs, go for it! -The [_Full Reference_](https://plotly.com/python/reference/) page contains descriptions of all of the supported trace and layout options. +This is a perfectly valid way to use `plotly.py` to build figures. On the other hand, if you would like to use an API that offers you a bit more assistance in the figure creation process, read on to learn about `graph objects`. -If working from the _Full Reference_ to build figures as Python dictionaries and lists suites your needs, go for it! This is a perfectly valid way to use plotly.py to build figures. On the other hand, if you would like an API that offers a bit more assistance, read on to learn about graph objects. +#### Figures as Graph Objects -#### Figures as graph objects +As an alternative to working with Python dictionaries, the `plotly.py` graphing library provides a hierarchy of classes called "graph objects" that may be used to construct figures. Graph objects have several benefits compared to plain Python dictionaries. -As an alternative to working with Python dictionaries, plotly.py provides a hierarchy of classes called "graph objects" that may be used to construct figures. Graph objects have several benefits compared to plain dictionaries. +1. Graph objects provide precise data validation. If you provide an invalid property name or an invalid property value as the key to a graph object, an exception will be raised with a helpful error message describing the problem. This is not the case if you use plain Python dictionaries and lists to build your figures. + +2. Graph objects contain descriptions of each valid property as Python `docstrings`. You can use these `docstrings` in the development environment of your choice to learn about the available properties as an alternative to consulting the online _Full Reference_. + +3. Properties of graph objects can be accessed using both dictionary-style key lookup (e.g. `fig["layout"]`) or class-style property access (e.g. `fig.layout`). -1. Graph objects provide precise data validation. So if you provide an invalid property name or an invalid property value, an exception will be raised with a helpful error message describing the problem. -2. Graph objects contain descriptions of each property as Python docstrings. You can use these docstrings to learn about the available properties as an alternative to consulting the _Full Reference_. -3. Properties of graph objects can be accessed using dictionary-style key lookup (e.g. `fig["layout"]`) or class-style property access (e.g. `fig.layout`). 4. Graph objects support higher-level convenience functions for making updates to already constructed figures, as described below. -Graph objects are stored in a hierarchy of modules under the `plotly.graph_objects` package. Here is an example of one way that the figure above could be constructed using graph objects. +**Graph objects are stored in a hierarchy of modules under the `plotly.graph_objects` package, so make sure to remember to `import plotly.graph_objects as go` when you want to use them.** + +Below you can find an example of one way that the figure in the example above could be specified using a graph object instead of a dictionary. ```python import plotly.graph_objects as go + fig = go.Figure( data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])], layout=go.Layout( - title=go.layout.Title(text="A Bar Chart") + title=go.layout.Title(text="A Figure Specified By A Graph Object") ) ) + fig.show() ``` -You can also create a graph object figure from a dictionary representation by passing the dictionary to the figure constructor. +You can also create a graph object figure from a dictionary representation by passing the dictionary to the `go.Figure` constructor. ```python import plotly.graph_objects as go -fig = go.Figure({ + +dict_of_fig = dict({ "data": [{"type": "bar", "x": [1, 2, 3], "y": [1, 3, 2]}], - "layout": {"title": {"text": "A Bar Chart"}} + "layout": {"title": {"text": "A Figure Specified By A Graph Object With A Dictionary"}} }) + +fig = go.Figure(dict_of_fig) + fig.show() ``` -Once you have a figure as a graph object, you can retrieve the dictionary representation using the `fig.to_dict()` method. You can also retrieve the JSON string representation using the `fig.to_json()` method. +##### Converting Graph Objects To Dictionaries and JSON + +Graph objects can be turned into their Python dictionary representation using the `fig.to_dict()` method. You can also retrieve the JSON string representation of a graph object using the `fig.to_json()` method. + +```python +import plotly.graph_objects as go + +fig = go.Figure( + data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])], + layout=go.Layout( + title=go.layout.Title(text="Converting Graph Objects To Dictionaries and JSON") + ) +) + +print("Dictionary Representation of A Graph Object:\n" + str(fig.to_dict())) + +print("\n\nJSON Representation of A Graph Object:\n" + str(fig.to_json())) +``` -### Creating figures +### Creating Figures -This section summarizes several ways to create new graph object figures with plotly.py +This section summarizes several ways to create new graph object figures with the `plotly.py` graphing library. #### Constructor -As demonstrated above, you can build a complete figure by passing trace and layout specifications to the `plotly.graph_objects.Figure` constructor. These trace and layout specifications can be either dictionaries or graph objects. Here, for example, the traces are specified using graph objects and the layout is specified as a dictionary. +As demonstrated above, you can build a complete figure by passing trace and layout specifications to the `plotly.graph_objects.Figure` constructor. These trace and layout specifications can be either dictionaries or graph objects. + +In the following example, the traces are specified using graph objects and the layout is specified as a dictionary. ```python import plotly.graph_objects as go + fig = go.Figure( data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])], - layout=dict(title=dict(text="A Bar Chart")) + layout=dict(title=dict(text="A Figure Specified By A Graph Object")) ) + fig.show() ``` -#### Plotly express +#### Plotly Express -Plotly express (included as the `plotly.express` module) is a high-level data exploration API that produces graph object figures. +[Plotly Express](https://plot.ly/python/plotly-express/) (included as the `plotly.express` module) is a high-level data exploration API that produces graph object figures. ```python import plotly.express as px + df = px.data.iris() -fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", title="A Plotly Express Figure") # If you print fig, you'll see that it's just a regular figure with data and layout # print(fig) @@ -135,45 +183,53 @@ fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") fig.show() ``` -#### Figure factories +#### Figure Factories -Figure factories (included in plotly.py in the `plotly.figure_factory` module) are functions that produce graph object figures, often to satisfy the needs of specialized domains. Here's an example of using the `create_quiver` figure factory to construct a graph object figure that displays a 2D quiver plot. +Figure factories (included in `plotly.py` in the `plotly.figure_factory` module) are functions that produce graph object figures, often to satisfy the needs of specialized domains. Here's an example of using the `create_quiver()` figure factory to construct a graph object figure that displays a 2D quiver plot. ```python import numpy as np import plotly.figure_factory as ff + x1,y1 = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2)) u1 = np.cos(x1)*y1 v1 = np.sin(x1)*y1 fig = ff.create_quiver(x1, y1, u1, v1) + fig.show() ``` -#### Make subplots +#### Make Subplots -The `plotly.subplots.make_subplots` function produces a graph object figure that is preconfigured with a grid of subplots that traces can be added to. The `add_trace` function will be discussed more below. +The `plotly.subplots.make_subplots()` function produces a graph object figure that is preconfigured with a grid of subplots that traces can be added to. The `add_trace()` function will be discussed more below. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) + fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1) fig.add_trace(go.Bar(y=[2, 1, 3]), row=1, col=2) + fig.show() ``` -### Updating figures +### Updating Figures -Regardless of how a graph object figure was constructed, it can be updated by adding additional traces and modifying its properties. +Regardless of how a graph object figure was constructed, it can be updated by adding additional traces to it and modifying its properties. -#### Adding traces +#### Adding Traces -New traces can be added to a graph object figure using the `add_trace` method. This method accepts a graph object trace (an instance of `go.Scatter`, `go.Bar`, etc.) and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially. +New traces can be added to a graph object figure using the `add_trace()` method. This method accepts a graph object trace (an instance of `go.Scatter`, `go.Bar`, etc.) and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially. ```python import plotly.graph_objects as go + fig = go.Figure() + fig.add_trace(go.Bar(x=[1, 2, 3], y=[1, 3, 2])) + fig.show() ``` @@ -181,8 +237,12 @@ You can also add traces to a figure produced by a figure factory or Plotly Expre ```python import plotly.express as px + df = px.data.iris() -fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") + +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", + title="Using The add_trace() method With A Plotly Express Figure") + fig.add_trace( go.Scatter( x=[2, 4], @@ -194,15 +254,18 @@ fig.add_trace( fig.show() ``` -#### Adding traces to subplots +#### Adding Traces To Subplots -If a figure was created using `plotly.subplots.make_subplots`, then the `row` and `col` argument to `add_trace` can be used to add a trace to a particular subplot. +If a figure was created using `plotly.subplots.make_subplots()`, then supplying the `row` and `col` arguments to `add_trace()` can be used to add a trace to a particular subplot. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) + fig.add_trace(go.Scatter(y=[4, 2, 1], mode="lines"), row=1, col=1) fig.add_trace(go.Bar(y=[2, 1, 3]), row=1, col=2) + fig.show() ``` @@ -210,43 +273,60 @@ This also works for figures created by Plotly Express using the `facet_row` and ```python import plotly.express as px + df = px.data.iris() -fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species") + +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species", + title="Adding Traces To Subplots Witin A Plotly Express Figure") + reference_line = go.Scatter(x=[2, 4], y=[4, 8], mode="lines", line=go.scatter.Line(color="gray"), showlegend=False) + fig.add_trace(reference_line, row=1, col=1) fig.add_trace(reference_line, row=1, col=2) fig.add_trace(reference_line, row=1, col=3) + fig.show() ``` -#### Add trace convenience methods +#### Add Trace Convenience Methods + +As an alternative to the `add_trace()` method, graph object figures have a family of methods of the form `add_{trace}` (where `{trace}` is the name of a trace type) for constructing and adding traces of each trace type. -As an alternative to the `add_trace` method, graph object figures have a family of methods of the form `add_{trace}`, where `{trace}` is the name of a trace type, for constructing and adding traces of each trace type. Here is the previous subplot example, adapted to add the scatter trace using `fig.add_scatter` and to add the bar trace using `fig.add_bar`. +Here is the previous subplot example, adapted to add the scatter trace using `fig.add_scatter()` and to add the bar trace using `fig.add_bar()`. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) + fig.add_scatter(y=[4, 2, 1], mode="lines", row=1, col=1) fig.add_bar(y=[2, 1, 3], row=1, col=2) + fig.show() ``` -#### Magic underscore notation +#### Magic Underscore Notation -To make it easier to work with nested properties graph object constructors, and many graph object methods, support magic underscore notation. This allows you to reference nested properties by joining together multiple nested property names with underscores. +To make it easier to work with nested properties, graph object constructors and many graph object methods support magic underscore notation. -For example, specifying the figure title in the figure constructor _without_ magic underscore notation requires setting the `layout` argument to `dict(title=dict(text="A Chart"))`. Similarly, setting the line color of a scatter trace requires setting the `marker` property to `dict(color="crimson")`. +This allows you to reference nested properties by joining together multiple nested property names with underscores. + +For example, specifying the figure title in the figure constructor _without_ magic underscore notation requires setting the `layout` argument to `dict(title=dict(text="A Chart"))`. + +Similarly, setting the line color of a scatter trace requires setting the `marker` property to `dict(color="crimson")`. ```python import plotly.graph_objects as go + fig = go.Figure( data=[go.Scatter(y=[1, 3, 2], line=dict(color="crimson"))], - layout=dict(title=dict(text="A Chart")) + layout=dict(title=dict(text="A Graph Object Figure With Magic Underscore Notation")) ) + fig.show() ``` @@ -254,10 +334,12 @@ With magic underscore notation, you can accomplish the same thing by passing the ```python import plotly.graph_objects as go + fig = go.Figure( data=[go.Scatter(y=[1, 3, 2], line_color="crimson")], - layout_title_text="A Chart" + layout_title_text="Another Graph Object Figure With Magic Underscore Notation" ) + fig.show() ``` @@ -265,45 +347,52 @@ Magic underscore notation is supported throughout the graph objects API, and it > Note: When you see keyword arguments with underscores passed to a graph object constructor or method, it is almost always safe to assume that it is an application of magic underscore notation. We have to say "almost always" rather than "always" because there are a few property names in the plotly schema that contain underscores: error_x, error_y, error_z, copy_xstyle, copy_ystyle, copy_zstyle, paper_bgcolor, and plot_bgcolor. These were added back in the early days of the library (2012-2013) before we standardized on banning underscores from property names. -#### The update layout method +#### Updating Figure Layouts -Graph object figures support an `update_layout` method that may be used to update multiple nested properties of a figure's layout. Here is an example of updating the text and font size of a figure's title using `update_layout`. +Graph object figures support an `update_layout()` method that may be used to update multiple nested properties of a figure's layout. + +Here is an example of updating the text and font size of a figure's title using `update_layout()`. ```python import plotly.graph_objects as go + fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2])) -fig.update_layout(title_text="A Bar Chart", + +fig.update_layout(title_text="Using update_layout() With Graph Object Figures", title_font_size=30) + fig.show() ``` -Note that the following `update_layout` operations are equivalent: +Note that the following `update_layout()` operations are equivalent: ```python -fig.update_layout(title_text="A Bar Chart", +fig.update_layout(title_text="update_layout() Syntax Example", title_font_size=30) -fig.update_layout(title_text="A Bar Chart", +fig.update_layout(title_text="update_layout() Syntax Example", title_font=dict(size=30)) -fig.update_layout(title=dict(text="A Bar Chart"), +fig.update_layout(title=dict(text="update_layout() Syntax Example"), font=dict(size=30)) -fig.update_layout({"title": {"text": "A Bar Chart", +fig.update_layout({"title": {"text": "update_layout() Syntax Example", "font": {"size": 30}}}) -fig.update_layout( - title=go.layout.Title(text="A Bar Chart", - font=go.layout.title.Font(size=30))); +fig.update_layout(title=go.layout.Title(text="update_layout() Syntax Example", + font=go.layout.title.Font(size=30))) ``` -#### The update traces method +#### Updating Traces + +Graph object figures support an `update_traces()` method that may be used to update multiple nested properties of one or more of a figure's traces. -Graph object figures support an `update_traces` method that may be used to update multiple nested properties of one or more of a figure's traces. To show some examples, we will start with a figure that contains bar and scatter traces across two subplots. +To show some examples, we will start with a figure that contains `bar` and `scatter` traces across two subplots. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) fig.add_scatter(y=[4, 2, 3.5], mode="markers", @@ -325,10 +414,11 @@ fig.add_bar(y=[1, 3, 2], fig.show() ``` -Note that both `scatter` and `bar` traces have a `marker.color` property to control their coloring. Here is an example of using `update_traces` to modify the color of all traces. +Note that both `scatter` and `bar` traces have a `marker.color` property to control their coloring. Here is an example of using `update_traces()` to modify the color of all traces. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) fig.add_scatter(y=[4, 2, 3.5], mode="markers", @@ -352,10 +442,11 @@ fig.update_traces(marker=dict(color="RoyalBlue")) fig.show() ``` -The `update_traces` method supports a `selector` argument to control which traces should be updated. Only traces with properties that match the selector will be updated. Here is an example of using a selector to only update the color of the `bar` traces +The `update_traces()` method supports a `selector` argument to control which traces should be updated. Only traces with properties that match the selector will be updated. Here is an example of using a selector to only update the color of the `bar` traces. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) fig.add_scatter(y=[4, 2, 3.5], mode="markers", @@ -384,6 +475,7 @@ Magic underscore notation can be used in the selector to match nested properties ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) fig.add_scatter(y=[4, 2, 3.5], mode="markers", @@ -408,10 +500,11 @@ fig.update_traces(marker_color="RoyalBlue", fig.show() ``` -For figures with subplots, the `update_traces` method also supports `row` and `col` arguments to control which traces should be updated. Only traces in the specified subplot row and column will be updated. Here is an example of updating the color of all traces in the second subplot column +For figures with subplots, the `update_traces()` method also supports `row` and `col` arguments to control which traces should be updated. Only traces in the specified subplot row and column will be updated. Here is an example of updating the color of all traces in the second subplot column. ```python from plotly.subplots import make_subplots + fig = make_subplots(rows=1, cols=2) fig.add_scatter(y=[4, 2, 3.5], mode="markers", @@ -436,87 +529,113 @@ fig.update_traces(marker=dict(color="RoyalBlue"), fig.show() ``` -The `update_traces` method can also be used on figures produced by figure factories or Plotly Express. Here's an example of updating the regression lines produced by Plotly Express to be dotted. +The `update_traces()` method can also be used on figures produced by figure factories or Plotly Express. Here's an example of updating the regression lines produced by Plotly Express to be dotted. ```python import pandas as pd import plotly.express as px + df = px.data.iris() -fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species", trendline="ols") + +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", + facet_col="species", trendline="ols", title="Using update_traces() With Plotly Express Figures") + fig.update_traces( line=dict(dash="dot", width=4), selector=dict(type="scatter", mode="lines")) + fig.show() ``` -### Overwrite existing properties when using update methods +### Overwrite Existing Properties When Using Update Methods -`update_layout` and `update_traces` have an `overwrite` keyword argument, defaulting to False, in which case updates are applied recursively to the _existing_ nested property structure. When set to True, the prior value of existing properties is overwritten with the provided value. +`update_layout()` and `update_traces()` have an `overwrite` keyword argument, defaulting to False, in which case updates are applied recursively to the _existing_ nested property structure. When set to True, the prior value of existing properties is overwritten with the provided value. -In the example below, the red color of markers is overwritten when updating `marker` in `update_traces` with `overwrite=True`. Note that setting instead `marker_opacity` with the magic underscore would not overwrite `marker_color` because properties would be overwritten starting only at the level of `marker.opacity`. +In the example below, the red color of markers is overwritten when updating `marker` in `update_traces()` with `overwrite=True`. Note that setting instead `marker_opacity` with the magic underscore would not overwrite `marker_color` because properties would be overwritten starting only at the level of `marker.opacity`. ```python import plotly.graph_objects as go + fig = go.Figure(go.Bar(x=[1, 2, 3], y=[6, 4, 9], marker_color="red")) # will be overwritten below -fig.update_traces( - overwrite=True, - marker={"opacity": 0.4} - ) + +fig.update_traces(overwrite=True, marker={"opacity": 0.4}) + fig.show() ``` -#### The for each trace method +#### Conditionally Updating Traces -Suppose the updates that you want to make to a collection of traces depend on the current values of certain trace properties. The `update_traces` method cannot handle this situation, but the `for_each_trace` method can. +Suppose the updates that you want to make to a collection of traces depend on the current values of certain trace properties. The `update_traces()` method cannot handle this situation, but the `for_each_trace()` method can! -As its first argument, the `for_each_trace` method accepts a function that accepts and updates one trace at a time. Like `update_traces`, `for_each_trace` also accepts `selector`, `row`, and `col` arguments to control which traces should be considered. +As its first argument, the `for_each_trace()` method accepts a function that accepts and updates one trace at a time. Like `update_traces()`, `for_each_trace()` also accepts `selector`, `row`, and `col` arguments to control which traces should be considered. -Here is an example of using `for_each_trace` to replace the equal-sign with a colon in the legend name of each trace in a figure produced by Plotly Express. +Here is an example of using `for_each_trace()` to convert the only markers for the `"setosa"` to square symbols in a Plotly Express Figure. + +**Note that this is possible because Plotly Express figures are made up of a separate trace for each column in the input data frame** ```python import pandas as pd import plotly.express as px + df = px.data.iris() -fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") + +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", + title="Conditionally Updating Traces In A Plotly Express Figure With for_each_trace()") fig.for_each_trace( - lambda trace: trace.update(name=trace.name.replace("=", ": ")), + lambda trace: trace.update(marker_symbol="square") if trace.name == "setosa" else (), ) fig.show() ``` -#### The update axis methods +#### Updating Figure Axes -Graph object figures support `update_xaxes` and `update_yaxes` methods that may be used to update multiple nested properties of one or more of a figure's axes. Here is an example of using `update_xaxes` to disable the vertical grid lines across all subplots in a figure produced by Plotly Express. +Graph object figures support `update_xaxes()` and `update_yaxes()` methods that may be used to update multiple nested properties of one or more of a figure's axes. Here is an example of using `update_xaxes()` to disable the vertical grid lines across all subplots in a figure produced by Plotly Express. ```python import pandas as pd import plotly.express as px + df = px.data.iris() -fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species") + +fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", + facet_col="species", title="Using update_xaxes() With A Plotly Express Figure") + fig.update_xaxes(showgrid=False) + fig.show() ``` -There are also `for_each_xaxis` and `for_each_yaxis` methods that are analogous to the `for_each_trace` method described above. For non-cartesian subplot types (e.g. polar), there are additional `update_{type}` and `for_each_{type}` methods (e.g. `update_polar`, `for_each_polar`). +There are also `for_each_xaxis()` and `for_each_yaxis()` methods that are analogous to the `for_each_trace()` method described above. For non-cartesian subplot types (e.g. polar), there are additional `update_{type}` and `for_each_{type}` methods (e.g. `update_polar()`, `for_each_polar()`). -### Other update methods +### Other Update Methods -`go` figures also support `update_layout_images` in order to [update background layout images](/python/images/), `update_annotations` in order to [update annotations](/python/text-and-annotations/#multiple-annotations), and `update-shapes` in order to [update shapes](/python/shapes/). +Figures created with the plotly.py graphing library also support: + - the `update_layout_images()` method in order to [update background layout images](/python/images/), + - `update_annotations()` in order to [update annotations](/python/text-and-annotations/#multiple-annotations), + - and `update-shapes()` in order to [update shapes](/python/shapes/). -#### Chaining figure operations +#### Chaining Figure Operations All of the figure update operations described above are methods that return a reference to the figure being modified. This makes it possible the chain multiple figure modification operations together into a single expression. -Here is an example of a chained expression that creates a faceted scatter plot with OLS trend lines using Plotly Express, sets the title font size using `update_layout`, disables vertical grid lines using `update_xaxes`, updates the width and dash pattern of the trend lines using `update_traces`, and then displays the figure using `show`. +Here is an example of a chained expression that creates: + - a faceted scatter plot with OLS trend lines using Plotly Express, + - sets the title font size using `update_layout()`, + - disables vertical grid lines using `update_xaxes()`, + - updates the width and dash pattern of the trend lines using `update_traces()`, + - and then displays the figure using `show()`. ```python import plotly.express as px + df = px.data.iris() + (px.scatter(df, x="sepal_width", y="sepal_length", color="species", - facet_col="species", trendline="ols", title="Iris Dataset") + facet_col="species", trendline="ols", + title="Chaining Multiple Figure Operations With A Plotly Express Figure") .update_layout(title_font_size=24) .update_xaxes(showgrid=False) .update_traces( @@ -525,23 +644,26 @@ df = px.data.iris() ).show() ``` -#### Property assignment +#### Property Assignment Trace and layout properties can be updated using property assignment syntax. Here is an example of setting the figure title using property assignment. ```python import plotly.graph_objects as go fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2])) -fig.layout.title.text = "A Bar Chart" +fig.layout.title.text = "Using Property Assignment Syntax With A Graph Object Figure" fig.show() ``` -And here is an example of updating the bar outline using property assignment +And here is an example of updating the bar outline using property assignment. ```python import plotly.graph_objects as go + fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2])) + fig.data[0].marker.line.width = 4 fig.data[0].marker.line.color = "black" + fig.show() ``` diff --git a/doc/python/renderers.md b/doc/python/renderers.md index ddd27bd8c11..47ac49334d6 100644 --- a/doc/python/renderers.md +++ b/doc/python/renderers.md @@ -5,8 +5,8 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.6 + format_version: '1.2' + jupytext_version: 1.3.2 kernelspec: display_name: Python 3 language: python @@ -20,32 +20,35 @@ jupyter: name: python nbconvert_exporter: python pygments_lexer: ipython3 - version: 3.7.3 + version: 3.7.0 plotly: - description: Displaying Figures from Python + description: Displaying Figures using Plotly's Python graphing library display_as: file_settings language: python + layout: base name: Displaying Figures + order: 1 page_type: example_index - layout: base permalink: python/renderers/ redirect_from: python/offline/ thumbnail: thumbnail/displaying-figures.png - order: 1 --- -### Displaying plotly figures -This section covers the many ways to display plotly figures from Python. At the highest level, there are three general approaches: +# Displaying Figures + +Plotly's Python graphing library, `plotly.py`, gives you a wide range of options for how and where to display your figures. + +In general, there are three different approaches you can take in order to display figures: 1. Using the renderers framework in the context of a script or notebook - 2. Using Dash in a web app context - 3. Using a `FigureWidget` in an ipywidgets context + 2. Using [Dash](https://dash.plot.ly) in a web app context + 3. Using a `FigureWidget` in an `ipywidgets` context Each of these approaches is discussed below. -### Displaying figures using the renderers framework +### Displaying Figures Using The renderers Framework -The renderers framework is a flexible approach for displaying plotly figures in a variety of contexts. To display a figure using the renderers framework, you call the `.show` method on a graph object figure, or pass the figure to the `plotly.io.show` function. With either approach, plotly.py will display the figure using the current default renderer(s). +The renderers framework is a flexible approach for displaying `plotly.py` figures in a variety of contexts. To display a figure using the renderers framework, you call the `.show()` method on a graph object figure, or pass the figure to the `plotly.io.show` function. With either approach, `plotly.py` will display the figure using the current default renderer(s). ```python import plotly.graph_objects as go @@ -67,15 +70,17 @@ fig = go.Figure( fig ``` -> To be precise, figures will display themselves using the current default renderer when the two following conditions are true. First, the last expression in a cell must evaluates to a figure. Second, plotly.py must be running from within an IPython kernel. +> To be precise, figures will display themselves using the current default renderer when the two following conditions are true. First, the last expression in a cell must evaluate to a figure. Second, `plotly.py` must be running from within an `IPython` kernel. + +**In many contexts, an appropriate renderer will be chosen automatically and you will not need to perform any additional configuration.** These contexts include the classic [Jupyter Notebook](https://jupyter.org/), [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) (provided the `jupyterlab-plotly` JupyterLab extension is installed), [Visual Studio Code notebooks](https://code.visualstudio.com/docs/python/jupyter-support), [Google Colaboratory](https://colab.research.google.com/notebooks/intro.ipynb), [Kaggle](https://www.kaggle.com/kernels) notebooks, [Azure](https://notebooks.azure.com/) notebooks, and the [Python interactive shell](https://www.python.org/shell/). -**In many contexts, an appropriate renderer will be chosen automatically and you will not need to perform any additional configuration.** These contexts include the classic Jupyter Notebook, JupyterLab (provided the `jupyterlab-plotly` JupyterLab extension is installed), Visual Studio Code notebooks, Colab, Kaggle notebooks, Azure notebooks, and the Python interactive shell. Additional contexts are supported by choosing a compatible renderer including the IPython console, QtConsole, Spyder, and more. +Additional contexts are supported by choosing a compatible renderer including the [IPython console](https://docs.spyder-ide.org/ipythonconsole.html), [QtConsole](https://qtconsole.readthedocs.io/en/stable/), [Spyder](https://www.spyder-ide.org/), and more. Next, we will show how to configure the default renderer. After that, we will describe all of the built-in renderers and discuss why you might choose to use each one. -> Note: The renderers framework is a generalization of the `plotly.offline.iplot` and `plotly.offline.plot` functions that were the recommended way to display figures prior to plotly.py version 4. These functions have been reimplemented using the renderers framework and are still supported for backward compatibility, but they will not be discussed here. +> Note: The `renderers` framework is a generalization of the `plotly.offline.iplot` and `plotly.offline.plot` functions that were the recommended way to display figures prior to `plotly.py` version 4. These functions have been reimplemented using the `renderers` framework and are still supported for backward compatibility, but they will not be discussed here. -#### Setting the default renderer +#### Setting The Default Renderer The current and available renderers are configured using the `plotly.io.renderers` configuration object. Display this object to see the current default renderer and the list of all available renderers. ```python @@ -83,19 +88,19 @@ import plotly.io as pio pio.renderers ``` -The default renderer that you see when you display `pio.renderers` might be different than what is shown here. This is because plotly.py attempts to autodetect an appropriate renderer at startup. You can change the default renderer by assigning the name of an available renderer to the `pio.renderers.default` property. For example, to switch to the `'browser'` renderer, which opens figures in a tab of the default web browser, you would run the following. +The default renderer that you see when you display `pio.renderers` might be different than what is shown here. This is because `plotly.py` attempts to autodetect an appropriate renderer at startup. You can change the default renderer by assigning the name of an available renderer to the `pio.renderers.default` property. For example, to switch to the `'browser'` renderer, which opens figures in a tab of the default web browser, you would run the following. -> Note: Default renderers persist for the duration of a single session, but they do not persist across sessions. If you are working in an IPython kernel, this means that default renderers will persist for the life of the kernel, but they will not persist across kernel restarts. +> Note: Default renderers persist for the duration of a single session, but they do not persist across sessions. If you are working in an `IPython` kernel, this means that default renderers will persist for the life of the kernel, but they will not persist across kernel restarts. ```python import plotly.io as pio pio.renderers.default = "browser" ``` -It is also possible to set the default renderer using a system environment variable. At startup, plotly.py checks for the existence of an environment variable named `PLOTLY_RENDERER`. If this environment variable is set to the name of an available renderer, this renderer is set as the default. +It is also possible to set the default renderer using a system environment variable. At startup, `plotly.py` checks for the existence of an environment variable named `PLOTLY_RENDERER`. If this environment variable is set to the name of an available renderer, this renderer is set as the default. -#### Overriding the default renderer -It is also possible to override the default renderer temporarily by passing the name of an available renderer as the `renderer` keyword argument to the `.show` method. Here is an example of displaying a figure using the `svg` renderer (described below) without changing the default renderer. +#### Overriding The Default Renderer +It is also possible to override the default renderer temporarily by passing the name of an available renderer as the `renderer` keyword argument to the `show()` method. Here is an example of displaying a figure using the `svg` renderer (described below) without changing the default renderer. ```python import plotly.graph_objects as go @@ -106,23 +111,23 @@ fig = go.Figure( fig.show(renderer="svg") ``` -#### The built-in renderers +#### Built-in Renderers In this section, we will describe the built-in renderers so that you can choose the one(s) that best suit your needs. -##### Interactive renderers -Interactive renderers display figures using the Plotly.js JavaScript library and are fully interactive, supporting pan, zoom, hover tooltips, etc. +##### Interactive Renderers +Interactive renderers display figures using the plotly.js JavaScript library and are fully interactive, supporting pan, zoom, hover tooltips, etc. ###### `notebook` -This renderer is intended for use in the classic [Jupyter Notebook](https://jupyter.org/install.html) (not JupyterLab). The full Plotly.js JavaScript library bundle is added to the notebook the first time a figure is rendered, so this renderer will work without an internet connection. +This renderer is intended for use in the classic [Jupyter Notebook](https://jupyter.org/install.html) (not JupyterLab). The full plotly.js JavaScript library bundle is added to the notebook the first time a figure is rendered, so this renderer will work without an Internet connection. -This renderer is a good choice for notebooks that will be exported to HTML files (Either using [nbconvert](https://nbconvert.readthedocs.io/en/latest/) or the "Download as HTML" menu action) because the exported HTML files will work without an internet connection. +This renderer is a good choice for notebooks that will be exported to HTML files (Either using [nbconvert](https://nbconvert.readthedocs.io/en/latest/) or the "Download as HTML" menu action) because the exported HTML files will work without an Internet connection. -> Note: Adding the Plotly.js bundle to the notebook does add a few megabytes to the notebook size, so if you can count on having an internet connection you may want to consider the `notebook_connected` renderer. +> Note: Adding the plotly.js bundle to the notebook adds a few megabytes to the notebook size. If you can count on always having an Internet connection, you may want to consider using the `notebook_connected` renderer if notebook size is a constraint. ###### `notebook_connected` -This renderer is the same as `notebook`, except the Plotly.js JavaScript library bundle is loaded from an online CDN location. This saves a few megabytes in notebook size, but an internet connection is required in order to display figures that are rendered this way. +This renderer is the same as `notebook` renderer, except the plotly.js JavaScript library bundle is loaded from an online CDN location. This saves a few megabytes in notebook size, but an Internet connection is required in order to display figures that are rendered this way. -This renderer is a good choice for notebooks that will be shared with [nbviewer](https://nbviewer.jupyter.org/) since users must have an active internet connection to access nbviewer in the first place. +This renderer is a good choice for notebooks that will be shared with [nbviewer](https://nbviewer.jupyter.org/) since users must have an active Internet connection to access nbviewer in the first place. ###### `kaggle` and `azure` These are aliases for `notebook_connected` because this renderer is a good choice for use with [Kaggle kernels](https://www.kaggle.com/docs/kernels) and [Azure Notebooks](https://notebooks.azure.com/). @@ -133,7 +138,7 @@ This is a custom renderer for use with [Google Colab](https://colab.research.goo ###### `browser` This renderer will open a figure in a browser tab using the default web browser. This renderer can only be used when the Python kernel is running locally on the same machine as the web browser, so it is not compatible with Jupyter Hub or online notebook services. -> Implementation Note 1: The "default browser" is the browser that is chosen by the Python [`webbrowser`](https://docs.python.org/3.7/library/webbrowser.html) module. +> Implementation Note 1: In this context, the "default browser" is the browser that is chosen by the Python [`webbrowser`](https://docs.python.org/3.7/library/webbrowser.html) module. > Implementation Note 2: The `browser` renderer works by setting up a single use local webserver on a local port. Since the webserver is shut down as soon as the figure is served to the browser, the figure will not be restored if the browser is refreshed. @@ -141,25 +146,25 @@ This renderer will open a figure in a browser tab using the default web browser. These renderers are the same as the `browser` renderer, but they force the use of a particular browser. ###### `iframe` and `iframe_connected` -These renderers write figures out as standalone HTML files and then display [`iframe`](https://www.w3schools.com/html/html_iframe.asp) elements that reference these HTML files. The `iframe` renderer will include the Plotly.js JavaScript bundle in each HTML file that is written, while the `iframe_connected` renderer includes only a reference to an online CDN location from which to load Plotly.js. Consequently, the `iframe_connected` renderer outputs files that are smaller than the `iframe` renderer, but it requires an internet connection while the `iframe` renderer can operate offline. +These renderers write figures out as standalone HTML files and then display [`iframe`](https://www.w3schools.com/html/html_iframe.asp) elements that reference these HTML files. The `iframe` renderer will include the plotly.js JavaScript bundle in each HTML file that is written, while the `iframe_connected` renderer includes only a reference to an online CDN location from which to load plotly.js. Consequently, the `iframe_connected` renderer outputs files that are smaller than the `iframe` renderer, but it requires an Internet connection while the `iframe` renderer can operate offline. -This renderer may be useful when working with notebooks than contain lots of large figures. When using the `notebook` or `notebook_connected` renderer, all of the data for all of the figures in a notebook are stored inline in the notebook itself. If this would result in a prohibitively large notebook size, an `iframe` or `iframe_connected` renderer could be used instead. With the iframe renderers, the figure data are stored in the individual HTML files rather than in the notebook itself, resulting in a smaller notebook size. +This renderer may be useful when working with notebooks than contain lots of large figures. When using the `notebook` or `notebook_connected` renderer, all of the data for all of the figures in a notebook are stored inline in the notebook itself. If this would result in a prohibitively large notebook size, an `iframe` or `iframe_connected` renderer could be used instead. With the `iframe` renderers, the figure data are stored in the individual HTML files rather than in the notebook itself, resulting in a smaller notebook size. -> Implementation Note: The HTML files written by the iframe renderers are stored in a subdirectory named `iframe_figures`. The HTML files are given names based on the execution number of the notebook cell that produced the figure. This means that each time a notebook kernel is restarted, any prior HTML files will be overwritten. This also means that you should not store multiple notebooks using an iframe renderer in the same directory, because this could result in figures from one notebook overwriting figures from another notebook. +> Implementation Note: The HTML files written by the `iframe` renderers are stored in a subdirectory named `iframe_figures`. The HTML files are given names based on the execution number of the notebook cell that produced the figure. This means that each time a notebook kernel is restarted, any prior HTML files will be overwritten. This also means that you should not store multiple notebooks using an `iframe` renderer in the same directory, because this could result in figures from one notebook overwriting figures from another notebook. ###### `plotly_mimetype` -The `plotly_mimetype` renderer creates a specification of the plotly figure (called a MIME-type bundle), and requests that the current user interface displays it. User interfaces that support this renderer include [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) (requires the [`jupyterlab-plotly`](https://www.npmjs.com/package/jupyterlab-plotly) extension), [nteract](https://nteract.io/), and the Visual Studio Code [notebook interface](https://code.visualstudio.com/docs/python/jupyter-support). +The `plotly_mimetype` renderer creates a specification of the figure (called a MIME-type bundle), and requests that the current user interface displays it. User interfaces that support this renderer include [JupyterLab](https://jupyterlab.readthedocs.io/en/stable/) (requires the [`jupyterlab-plotly`](https://www.npmjs.com/package/jupyterlab-plotly) extension), [nteract](https://nteract.io/), and the Visual Studio Code [notebook interface](https://code.visualstudio.com/docs/python/jupyter-support). ###### `jupyterlab`, `nteract`, and `vscode` These are aliases for `plotly_mimetype` since this renderer is a good choice when working in JupyterLab, nteract, and the Visual Studio Code notebook interface. -##### Static image renderers -A set of renderers is provided for displaying figures as static images. These renderers all rely on the orca static image export utility. See the [Static Image Export](https://plotly.com/python/static-image-export/) page for more information on getting set up with orca. +##### Static Image Renderers +A set of renderers is provided for displaying figures as static images. These renderers all rely on the [orca](https://github.com/plotly/orca) static image export utility. See the [Static Image Export](https://plot.ly/python/static-image-export/) page for more information on getting set up with [orca]. ###### `png`, `jpeg`, and `svg` -These renderers display figures as static PNG, JPEG, and SVG images respectively. These renderers are useful for user interfaces that do not support inline HTML output, but do support inline static images. Examples include the [QtConsole](https://qtconsole.readthedocs.io/en/stable/), [Spyder](https://www.spyder-ide.org/), and the PyCharm [notebook interface](https://www.jetbrains.com/help/pycharm/jupyter-notebook-support.html). +These renderers display figures as static `.png`, `.jpeg`, and `.svg` files, respectively. These renderers are useful for user interfaces that do not support inline HTML output, but do support inline static images. Examples include the [QtConsole](https://qtconsole.readthedocs.io/en/stable/), [Spyder](https://www.spyder-ide.org/), and the PyCharm [notebook interface](https://www.jetbrains.com/help/pycharm/jupyter-notebook-support.html). ```python import plotly.graph_objects as go @@ -170,19 +175,18 @@ fig = go.Figure( fig.show(renderer="png") ``` -###### `pdf` -This renderer displays figures as static PDF files. This is especially useful for notebooks that will be exported to PDF files using the LaTeX export capabilities of nbconvert. +###### PDF +This renderer displays figures as static PDF files. This is especially useful for notebooks that will be exported to PDF files using the LaTeX export capabilities of [`nbconvert`](https://nbconvert.readthedocs.io/en/latest/). -##### Other renderers -Other miscellaneous renderers +##### Other Miscellaneous Renderers -###### `json` -In editors that support it (JupyterLab, nteract, and the Visual Studio Code notebook interface), this renderer displays the JSON representation of a figure in a collapsible interactive tree structure. This can be very useful for examining the structure of complex figures +###### JSON +In editors that support it (JupyterLab, nteract, and the Visual Studio Code notebook interface), this renderer displays the JSON representation of a figure in a collapsible interactive tree structure. This can be very useful for examining the structure of complex figures. -##### Multiple renderers -You can specify that multiple renderers should be used by joining their names on `"+"` characters. This is useful when writing code that needs to support multiple contexts. For example, if a notebook specifies a default renderer string of `"notebook+plotly_mimetype+pdf"`then this notebook would be able to run in the classic Jupyter Notebook, in JupyterLab, and it would support being exported to PDF using nbconvert. +##### Multiple Renderers +You can specify that multiple renderers should be used by joining their names on `"+"` characters. This is useful when writing code that needs to support multiple contexts. For example, if a notebook specifies a default renderer string of `"notebook+plotly_mimetype+pdf"`then this notebook would be able to run in the classic Jupyter Notebook, in JupyterLab, and it would support being exported to PDF using `nbconvert`. -#### Customizing built-in renderers +#### Customizing Built-In Renderers Most built-in renderers have configuration options to customize their behavior. To view a description of a renderer, including its configuration options, access the renderer object using dictionary-style key lookup on the `plotly.io.renderers` configuration object and then display it. Here is an example of accessing and displaying the `png` renderer. ```python @@ -211,7 +215,7 @@ fig = go.Figure( fig.show() ``` -You can also override the values of renderer parameters temporarily by passing them as keyword arguments to the `.show` method. For example +You can also override the values of renderer parameters temporarily by passing them as keyword arguments to the `show()` method. For example ```python import plotly.graph_objects as go @@ -223,12 +227,29 @@ fig = go.Figure( fig.show(renderer="png", width=800, height=300) ``` -### Displaying figures using Dash -Dash is a Python framework for building web applications, and it provides built-in support for displaying Plotly figures. See the [Dash User Guide](https://dash.plotly.com/) for more information. +### Displaying Figures Using Dash + +[Dash](https://dash.plot.ly) is a Python framework for building web applications, and it provides built-in support for displaying figures created with Plotly's graphing libraries. See the [Dash User Guide](https://dash.plot.ly/) for more information. + +It is important to note that Dash does not use the renderers framework discussed above, so you should not try to use the `.show()` figure method or the `plotly.io.show` function to render figures inside Dash applications. + +Instead, pass your figure as the `figure` parameter to the [`dcc.Graph`](https://dash.plot.ly/dash-core-components/graph) component, which is part of the [Dash Core Components](https://dash.plot.ly/dash-core-components) library. The code below demonstrates how to do this. + + +import dash_core_components as dcc +import plotly.graph_objs as go + +fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])]) + +dcc.Graph( + id='example-graph-2', + figure=fig + ) + -It is important to note that Dash does not use the renderers framework discussed above, so you should not use the `.show` figure method or the `plotly.io.show` function inside Dash applications. +## Displaying Figures Using `ipywidgets` +Plotly figures can be displayed in [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/) contexts using `plotly.graph_objects.FigureWidget` objects. `FigureWidget` is a figure graph object (just like `plotly.graph_objects.Figure`), so you can add traces to it and update it just like a regular `Figure`. But `FigureWidget` is also an `ipywidgets` object, which means that you can display it alongside other `ipywidgets` to build user interfaces right in the notebook. -## Displaying figures using ipywidgets -Plotly figures can be displayed in [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/) contexts using `plotly.graph_objects.FigureWidget` objects. `FigureWidget` is a figure graph object (Just like `plotly.graph_objects.Figure`) so you can add traces to it and update it just like a regular `Figure`. But `FigureWidget` is also an ipywidgets object, which means that you can display it alongside other ipywidgets to build user interfaces right in the notebook. See the [Plotly FigureWidget Overview](https://plotly.com/python/figurewidget/) for more information on integrating plotly figures with ipywidgets. +See the [Plotly FigureWidget Overview](https://plot.ly/python/figurewidget/) for more information on integrating `plotly.py` figures with `ipywidgets`. -It is important to note that `FigureWidget` does not use the renderers framework discussed above, so you should not use the `.show` figure method or the `plotly.io.show` function on `FigureWidget` objects. +It is important to note that `FigureWidget` does not use the renderers framework discussed above, so you should not use the `show()` figure method or the `plotly.io.show` function on `FigureWidget` objects. diff --git a/doc/python/subplots.md b/doc/python/subplots.md index 4860ef314f7..4e0c92fd8c8 100644 --- a/doc/python/subplots.md +++ b/doc/python/subplots.md @@ -5,8 +5,8 @@ jupyter: text_representation: extension: .md format_name: markdown - format_version: '1.1' - jupytext_version: 1.1.6 + format_version: '1.2' + jupytext_version: 1.3.2 kernelspec: display_name: Python 3 language: python @@ -20,10 +20,10 @@ jupyter: name: python nbconvert_exporter: python pygments_lexer: ipython3 - version: 3.7.3 + version: 3.7.0 plotly: - description: How to make subplots in python. Examples of stacked, custom-sized, - gridded, and annotated subplts. + description: How to make subplots in with Plotly's Python graphing library. Examples + of stacked, custom-sized, gridded, and annotated subplots. display_as: file_settings language: python layout: base @@ -37,9 +37,9 @@ jupyter: #### Simple Subplot -Figures with subplots are created using the `make_subplots` function from the `plotly.subplots` module. +Figures with subplots are created using the `make_subplots` function from the `plotly.subplots` module. -Here is an example of creating a figure with two scatter traces in side-by-side subplots. +Here is an example of creating a figure that includes two `scatter` traces which are side-by-side since there are 2 columns and 1 row in the subplot layout. ```python from plotly.subplots import make_subplots @@ -57,13 +57,13 @@ fig.add_trace( row=1, col=2 ) -fig.update_layout(height=600, width=800, title_text="Subplots") +fig.update_layout(height=600, width=800, title_text="Side By Side Subplots") fig.show() ``` #### Stacked Subplots -Here is an example of creating a figure with two vertically stacked subplots. +Here is an example of creating a figure with subplots that are stacked on top of each other since there are 3 rows and 1 column in the subplot layout. ```python from plotly.subplots import make_subplots @@ -87,13 +87,13 @@ fig.append_trace(go.Scatter( ), row=3, col=1) -fig.update_layout(height=600, width=600, title_text="Stacked subplots") +fig.update_layout(height=600, width=600, title_text="Stacked Subplots") fig.show() ``` #### Multiple Subplots -Here is an example of creating a 2 x 2 subplot grid and populating each subplot with a single scatter trace. +Here is an example of creating a 2 x 2 subplot grid and populating each subplot with a single `scatter` trace. ```python import plotly.graph_objects as go @@ -147,7 +147,7 @@ fig.update_layout(height=500, width=700, fig.show() ``` -#### Simple Subplot with Annotations +#### Subplots with Annotations ```python from plotly.subplots import make_subplots @@ -177,15 +177,15 @@ fig.add_trace( row=1, col=2 ) -fig.update_layout(height=600, width=800, title_text="Annotations and subplots") +fig.update_layout(height=600, width=800, title_text="Subplots with Annotations") fig.show() ``` -#### Side by Side Subplot +#### Customize Subplot Column Widths and Row Heights The `column_widths` argument to `make_subplots` can be used to customize the relative widths of the columns in a subplot grid. It should be set to a list of numbers with a length that matches the `cols` argument. These number will be normalized, so that they sum to 1, and used to compute the relative widths of the subplot grid columns. The `row_heights` argument serves the same purpose for controlling the relative heights of rows in the subplot grid. -Here is an example of creating a figure with two scatter traces in side-by-side subplots, where the left subplot is wider that the right. +Here is an example of creating a figure with two scatter traces in side-by-side subplots. The left subplot is set to be wider than the right one. ```python import plotly.graph_objects as go @@ -249,9 +249,9 @@ Here is an example that creates a figure with 3 vertically stacked subplots with from plotly.subplots import make_subplots import plotly.graph_objects as go -fig = make_subplots( - rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.02 -) +fig = make_subplots(rows=3, cols=1, + shared_xaxes=True, + vertical_spacing=0.02) fig.add_trace(go.Scatter(x=[0, 1, 2], y=[10, 11, 12]), row=3, col=1) @@ -270,7 +270,7 @@ fig.show() #### Subplots with Shared Y-Axes The `shared_yaxes` argument to `make_subplots` can be used to link the y axes of subplots in the resulting figure. -Here is an example that creates a figure with a 2 x 2 subplot grid, where the yaxes of each row are linked. +Here is an example that creates a figure with a 2 x 2 subplot grid, where the y axes of each row are linked. ```python @@ -346,7 +346,7 @@ fig.show() ``` #### Multiple Custom Sized Subplots -If the `print_grid` argument to `make_subplots` is set to `True`, then an text representation of the subplot grid will be printed. +If the `print_grid` argument to `make_subplots` is set to `True`, then a text representation of the subplot grid will be printed. Here is an example that uses the `rowspan` and `colspan` subplot options to create a custom subplot layout with subplots of mixed sizes. The `print_grid` argument is set to `True` so that the subplot grid is printed to the screen. @@ -363,8 +363,7 @@ fig = make_subplots( [{}, {}]], print_grid=True) -fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(1,1)"), - row=1, col=1) +fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(1,1)"), row=1, col=1) fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(1,2)"), row=1, col=2) fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(2,1)"), row=2, col=1) fig.add_trace(go.Scatter(x=[1, 2], y=[1, 2], name="(3,1)"), row=3, col=1) @@ -409,7 +408,8 @@ fig.add_trace(go.Barpolar(theta=[0, 45, 90], r=[2, 3, 1]), fig.add_trace(go.Pie(values=[2, 3, 1]), row=2, col=1) -fig.add_trace(go.Scatter3d(x=[2, 3, 1], y=[0, 0, 0], z=[0.5, 1, 2], mode="lines"), +fig.add_trace(go.Scatter3d(x=[2, 3, 1], y=[0, 0, 0], + z=[0.5, 1, 2], mode="lines"), row=2, col=2) fig.update_layout(height=700, showlegend=False) @@ -440,7 +440,8 @@ fig.add_trace(go.Barpolar(theta=[0, 45, 90], r=[2, 3, 1]), fig.add_trace(go.Pie(values=[2, 3, 1]), row=2, col=1) -fig.add_trace(go.Scatter3d(x=[2, 3, 1], y=[0, 0, 0], z=[0.5, 1, 2], mode="lines"), +fig.add_trace(go.Scatter3d(x=[2, 3, 1], y=[0, 0, 0], + z=[0.5, 1, 2], mode="lines"), row=2, col=2) fig.update_layout(height=700, showlegend=False)