Skip to content

Commit 3794f72

Browse files
author
Joseph Damiba
committed
fixups
1 parent f28433d commit 3794f72

File tree

1 file changed

+76
-43
lines changed

1 file changed

+76
-43
lines changed

doc/python/creating-and-updating-figures.md

Lines changed: 76 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ jupyter:
55
text_representation:
66
extension: .md
77
format_name: markdown
8-
format_version: "1.1"
9-
jupytext_version: 1.1.1
8+
format_version: '1.2'
9+
jupytext_version: 1.3.2
1010
kernelspec:
1111
display_name: Python 3
1212
language: python
@@ -20,42 +20,42 @@ jupyter:
2020
name: python
2121
nbconvert_exporter: python
2222
pygments_lexer: ipython3
23-
version: 3.7.3
23+
version: 3.7.0
2424
plotly:
2525
description: Creating and Updating Figures with Plotly's Python graphing library
2626
display_as: file_settings
2727
language: python
2828
layout: base
2929
name: Creating and Updating Figures
30+
order: 2
3031
page_type: example_index
3132
permalink: python/creating-and-updating-figures/
3233
redirect_from:
33-
- python/user-guide/
34-
- python/user-g/
34+
- python/user-guide/
35+
- python/user-g/
3536
thumbnail: thumbnail/creating-and-updating-figures.png
3637
v4upgrade: true
37-
order: 2
3838
---
3939

4040
### Representing Figures
4141

42-
The goal of the `plotly.py` graphing library is to provide a pleasant Python interface for creating figure specifications for display using the `plotly.js` JavaScript library.
42+
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.
4343

4444
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.
4545

46-
Therefore, 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.
46+
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.
4747

4848
#### Figures As Dictionaries
4949

50-
The `fig` dictonary in the example below describes a figure containing a single `bar` trace and a title.
50+
The `fig` dictonary in the example below describes a figure. It contains a single `bar` trace and a title.
5151

5252
```python
53-
fig = {
53+
fig = dict({
5454
"data": [{"type": "bar",
5555
"x": [1, 2, 3],
5656
"y": [1, 3, 2]}],
57-
"layout": {"title": {"text": "A Bar Chart"}}
58-
}
57+
"layout": {"title": {"text": "A Figure Specified By Python Dictionary"}}
58+
})
5959

6060
# To display the figure defined by this dict, use the low-level plotly.io.show function
6161
import plotly.io as pio
@@ -65,39 +65,45 @@ pio.show(fig)
6565

6666
Let's take a closer look at structure of the `fig` dictionary in order to better understand how `plotly.py` figures are built.
6767

68-
The first thing to notice is that the `fig` dictionary contains two keys. The `"data"` key stores a list of dictionaries while the `"layout"` key stores a dictionary.
68+
##### The `"data"` Key
6969

70-
The `"data"` key stores a list of dictonaries because a figure can be made up of multiple individual traces. Each trace specification dictionary in the `"data"` list 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 dictionary are used to configure the properties of the trace of this type.
70+
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.
7171

72-
The`"layout"` key stores 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.
72+
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.
73+
74+
##### The `"layout"` Key
75+
76+
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.
7377

7478
The [_Full Reference_](https://plot.ly/python/reference/) page contains descriptions of all of the supported trace and layout attributes and configuration options.
7579

7680
If working from the _Full Reference_ to build figures as Python dictionaries and lists suites your needs, go for it!
7781

78-
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`.
82+
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`.
7983

8084
#### Figures as Graph Objects
8185

8286
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.
8387

84-
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 to build your figures.
88+
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.
8589

86-
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_.
90+
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_.
8791

8892
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`).
8993

9094
4. Graph objects support higher-level convenience functions for making updates to already constructed figures, as described below.
9195

92-
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 in the example above could be constructed using graph objects.
96+
**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.**
97+
98+
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.
9399

94100
```python
95101
import plotly.graph_objects as go
96102

97103
fig = go.Figure(
98104
data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
99105
layout=go.Layout(
100-
title=go.layout.Title(text="A Bar Chart")
106+
title=go.layout.Title(text="A Figure Specified By A Graph Object")
101107
)
102108
)
103109

@@ -109,17 +115,36 @@ You can also create a graph object figure from a dictionary representation by pa
109115
```python
110116
import plotly.graph_objects as go
111117

112-
fig = go.Figure({
118+
dict_of_fig = dict({
113119
"data": [{"type": "bar",
114120
"x": [1, 2, 3],
115121
"y": [1, 3, 2]}],
116-
"layout": {"title": {"text": "A Bar Chart"}}
122+
"layout": {"title": {"text": "A Figure Specified By A Graph Object With A Dictionary"}}
117123
})
118124

125+
fig = go.Figure(dict_of_fig)
126+
119127
fig.show()
120128
```
121129

122-
Once you have a figure as a graph object, you can retrieve the Python dictionary representation using the `fig.to_dict()` method. You can also retrieve the JSON string representation using the `fig.to_json()` method.
130+
##### Converting Graph Objects To Dictionaries and JSON
131+
132+
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.
133+
134+
```python
135+
import plotly.graph_objects as go
136+
137+
fig = go.Figure(
138+
data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
139+
layout=go.Layout(
140+
title=go.layout.Title(text="Converting Graph Objects To Dictionaries and JSON")
141+
)
142+
)
143+
144+
print("Dictionary Representation of A Graph Object:\n" + str(fig.to_dict()))
145+
146+
print("\n\nJSON Representation of A Graph Object:\n" + str(fig.to_json()))
147+
```
123148

124149
### Creating Figures
125150

@@ -136,7 +161,7 @@ import plotly.graph_objects as go
136161

137162
fig = go.Figure(
138163
data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],
139-
layout=dict(title=dict(text="A Bar Chart"))
164+
layout=dict(title=dict(text="A Figure Specified By A Graph Object"))
140165
)
141166

142167
fig.show()
@@ -150,7 +175,7 @@ fig.show()
150175
import plotly.express as px
151176

152177
df = px.data.iris()
153-
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
178+
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", title="A Plotly Express Figure")
154179

155180
# If you print fig, you'll see that it's just a regular figure with data and layout
156181
# print(fig)
@@ -192,7 +217,7 @@ fig.show()
192217

193218
### Updating Figures
194219

195-
Regardless of how a graph object figure was constructed, it can be updated by adding additional traces and modifying its properties.
220+
Regardless of how a graph object figure was constructed, it can be updated by adding additional traces to it and modifying its properties.
196221

197222
#### Adding Traces
198223

@@ -215,7 +240,8 @@ import plotly.express as px
215240

216241
df = px.data.iris()
217242

218-
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
243+
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
244+
title="Using The add_trace() method With A Plotly Express Figure")
219245

220246
fig.add_trace(
221247
go.Scatter(
@@ -250,7 +276,8 @@ import plotly.express as px
250276

251277
df = px.data.iris()
252278

253-
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species")
279+
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species",
280+
title="Adding Traces To Subplots Witin A Plotly Express Figure")
254281

255282
reference_line = go.Scatter(x=[2, 4],
256283
y=[4, 8],
@@ -297,7 +324,7 @@ import plotly.graph_objects as go
297324

298325
fig = go.Figure(
299326
data=[go.Scatter(y=[1, 3, 2], line=dict(color="crimson"))],
300-
layout=dict(title=dict(text="A Chart"))
327+
layout=dict(title=dict(text="A Graph Object Figure With Magic Underscore Notation"))
301328
)
302329

303330
fig.show()
@@ -310,7 +337,7 @@ import plotly.graph_objects as go
310337

311338
fig = go.Figure(
312339
data=[go.Scatter(y=[1, 3, 2], line_color="crimson")],
313-
layout_title_text="A Chart"
340+
layout_title_text="Another Graph Object Figure With Magic Underscore Notation"
314341
)
315342

316343
fig.show()
@@ -331,7 +358,7 @@ import plotly.graph_objects as go
331358

332359
fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
333360

334-
fig.update_layout(title_text="A Bar Chart",
361+
fig.update_layout(title_text="Using update_layout() With Graph Object Figures",
335362
title_font_size=30)
336363

337364
fig.show()
@@ -340,20 +367,20 @@ fig.show()
340367
Note that the following `update_layout()` operations are equivalent:
341368

342369
```python
343-
fig.update_layout(title_text="A Bar Chart",
370+
fig.update_layout(title_text="update_layout() Syntax Example",
344371
title_font_size=30)
345372

346-
fig.update_layout(title_text="A Bar Chart",
373+
fig.update_layout(title_text="update_layout() Syntax Example",
347374
title_font=dict(size=30))
348375

349376

350-
fig.update_layout(title=dict(text="A Bar Chart"),
377+
fig.update_layout(title=dict(text="update_layout() Syntax Example"),
351378
font=dict(size=30))
352379

353-
fig.update_layout({"title": {"text": "A Bar Chart",
380+
fig.update_layout({"title": {"text": "update_layout() Syntax Example",
354381
"font": {"size": 30}}})
355382

356-
fig.update_layout(title=go.layout.Title(text="A Bar Chart",
383+
fig.update_layout(title=go.layout.Title(text="update_layout() Syntax Example",
357384
font=go.layout.title.Font(size=30)))
358385
```
359386

@@ -510,7 +537,8 @@ import plotly.express as px
510537

511538
df = px.data.iris()
512539

513-
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species", trendline="ols")
540+
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
541+
facet_col="species", trendline="ols", title="Using update_traces() With Plotly Express Figures")
514542

515543
fig.update_traces(
516544
line=dict(dash="dot", width=4),
@@ -542,18 +570,21 @@ Suppose the updates that you want to make to a collection of traces depend on th
542570

543571
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.
544572

545-
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.
573+
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.
574+
575+
**Note that this is possible because Plotly Express figures are made up of a separate trace for each column in the input data frame**
546576

547577
```python
548578
import pandas as pd
549579
import plotly.express as px
550580

551581
df = px.data.iris()
552582

553-
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
583+
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
584+
title="Conditionally Updating Traces In A Plotly Express Figure With for_each_trace()")
554585

555586
fig.for_each_trace(
556-
lambda trace: trace.update(name=trace.name.replace("=", ": ")),
587+
lambda trace: trace.update(marker_symbol="square") if trace.name == "setosa" else (),
557588
)
558589

559590
fig.show()
@@ -569,7 +600,8 @@ import plotly.express as px
569600

570601
df = px.data.iris()
571602

572-
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", facet_col="species")
603+
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
604+
facet_col="species", title="Using update_xaxes() With A Plotly Express Figure")
573605

574606
fig.update_xaxes(showgrid=False)
575607

@@ -602,7 +634,8 @@ import plotly.express as px
602634
df = px.data.iris()
603635

604636
(px.scatter(df, x="sepal_width", y="sepal_length", color="species",
605-
facet_col="species", trendline="ols", title="Iris Dataset")
637+
facet_col="species", trendline="ols",
638+
title="Chaining Multiple Figure Operations With A Plotly Express Figure")
606639
.update_layout(title_font_size=24)
607640
.update_xaxes(showgrid=False)
608641
.update_traces(
@@ -618,7 +651,7 @@ Trace and layout properties can be updated using property assignment syntax. Her
618651
```python
619652
import plotly.graph_objects as go
620653
fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
621-
fig.layout.title.text = "A Bar Chart"
654+
fig.layout.title.text = "Using Property Assignment Syntax With A Graph Object Figure"
622655
fig.show()
623656
```
624657

0 commit comments

Comments
 (0)