Skip to content

Commit 77e76af

Browse files
committed
Made variable state shared across codeblocks and cleaned up previous fixes to imports/variables missing in subsequent code blocks.
1 parent 7e8a638 commit 77e76af

11 files changed

+10
-89
lines changed

bin/run_markdown.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -206,11 +206,15 @@ def _report(condition, message):
206206
def _run_all_blocks(args, code_blocks, stem=None, block_number=None):
207207
"""Run blocks found in a file."""
208208
execution_results = []
209+
env = {
210+
"__name__": "__main__",
211+
"__file__": "<markdown_code>",
212+
}
209213
figure_counter = 0
210214
for i, block in enumerate(code_blocks):
211215
if block_number is None:
212216
_report(args.verbose > 1, f"- Executing block {i}/{len(code_blocks)}")
213-
figure_counter, result = _run_code(block["code"], args.outdir, figure_counter, stem)
217+
figure_counter, result = _run_code(block["code"], args.outdir, figure_counter, stem, env)
214218
execution_results.append(result)
215219
_report(args.verbose > 0 and bool(result["error"]), f" - Warning: block {i} had an error")
216220
_report(args.verbose > 1 and bool(result["images"]), f" - Generated {len(result['images'])} image(s)")
@@ -224,7 +228,7 @@ def _run_all_blocks(args, code_blocks, stem=None, block_number=None):
224228
return execution_results
225229

226230

227-
def _run_code(code, output_dir, figure_counter, stem):
231+
def _run_code(code, output_dir, figure_counter, stem, exec_globals):
228232
"""Execute code capturing output and generated files."""
229233
# Capture stdout and stderr
230234
stdout_buffer = io.StringIO()
@@ -239,10 +243,10 @@ def _run_code(code, output_dir, figure_counter, stem):
239243
try:
240244

241245
# Create a namespace for code execution
242-
exec_globals = {
243-
"__name__": "__main__",
244-
"__file__": "<markdown_code>",
245-
}
246+
# exec_globals = {
247+
# "__name__": "__main__",
248+
# "__file__": "<markdown_code>",
249+
# }
246250

247251
# Execute the code with output capture
248252
with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):

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

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -372,10 +372,6 @@ fig.show()
372372
Note that the following `update_layout()` operations are equivalent:
373373

374374
```python
375-
import plotly.graph_objects as go
376-
377-
fig = go.Figure(data=go.Bar(x=[1, 2, 3], y=[1, 3, 2]))
378-
379375
fig.update_layout(title_text="update_layout() Syntax Example",
380376
title_font_size=30)
381377

doc/python/ecdf-plots.md

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,6 @@ In `standard` mode (the default), the right-most point is at 1 (or the total cou
9696

9797
```python
9898
import plotly.express as px
99-
df = px.data.tips()
10099
fig = px.ecdf(df, x=[1,2,3,4], markers=True, ecdfmode="standard",
101100
title="ecdfmode='standard' (Y=fraction at or below X value, this the default)")
102101
fig.show()
@@ -106,7 +105,6 @@ In `reversed` mode, the right-most point is at 1 (or the total count/sum, depend
106105

107106
```python
108107
import plotly.express as px
109-
df = px.data.tips()
110108
fig = px.ecdf(df, x=[1,2,3,4], markers=True, ecdfmode="reversed",
111109
title="ecdfmode='reversed' (Y=fraction at or above X value)")
112110
fig.show()
@@ -116,7 +114,6 @@ In `complementary` mode, the right-most point is at 0 and no points are at 1 (or
116114

117115
```python
118116
import plotly.express as px
119-
df = px.data.tips()
120117
fig = px.ecdf(df, x=[1,2,3,4], markers=True, ecdfmode="complementary",
121118
title="ecdfmode='complementary' (Y=fraction above X value)")
122119
fig.show()

doc/python/figure-introspection.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,6 @@ print(full_fig.data[0])
117117
We see that this is an instance of `go.Scatter` (as expected, given the input) and that it has an attribute we've maybe never heard of called `cliponaxis` which by default seems to be set to `True` in this case. Let's find out more about this attribute using the built-in Python `help()` function
118118

119119
```python
120-
import plotly.graph_objects as go
121120
help(go.Scatter.cliponaxis)
122121
```
123122

@@ -131,7 +130,6 @@ fig.show()
131130
We can use this technique (of making a figure, and querying Plotly.js for the "full" version of that figure, and then exploring the attributes that are automatically set for us) to learn more about the range of possibilities that the figure schema makes available. We can drill down into `layout` attributes also:
132131

133132
```python
134-
import plotly.graph_objects as go
135133
help(go.layout.XAxis.autorange)
136134
```
137135

doc/python/figurewidget.md

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -56,26 +56,14 @@ f
5656
Add traces or update the layout and then watch the output above update in real time.
5757

5858
```python
59-
import plotly.graph_objects as go
60-
f = go.FigureWidget()
61-
6259
f.add_scatter(y=[2, 1, 4, 3])
6360
```
6461

6562
```python
66-
import plotly.graph_objects as go
67-
f = go.FigureWidget()
68-
f.add_scatter(y=[2, 1, 4, 3])
69-
7063
f.add_bar(y=[1, 4, 3, 2])
7164
```
7265

7366
```python
74-
import plotly.graph_objects as go
75-
f = go.FigureWidget()
76-
f.add_scatter(y=[2, 1, 4, 3])
77-
f.add_bar(y=[1, 4, 3, 2])
78-
7967
f.layout.title = 'Hello FigureWidget'
8068
```
8169

@@ -85,42 +73,18 @@ f.layout.title = 'Hello FigureWidget'
8573
#### Update the Data and the Layout
8674

8775
```python
88-
import plotly.graph_objects as go
89-
f = go.FigureWidget()
90-
f.add_scatter(y=[2, 1, 4, 3])
91-
f.add_bar(y=[1, 4, 3, 2])
92-
f.layout.title = 'Hello FigureWidget'
93-
9476
# update scatter data
9577
scatter = f.data[0]
9678
scatter.y = [3, 1, 4, 3]
9779
```
9880

9981
```python
100-
import plotly.graph_objects as go
101-
f = go.FigureWidget()
102-
f.add_scatter(y=[2, 1, 4, 3])
103-
f.add_bar(y=[1, 4, 3, 2])
104-
f.layout.title = 'Hello FigureWidget'
105-
scatter = f.data[0]
106-
scatter.y = [3, 1, 4, 3]
107-
10882
# update bar data
10983
bar = f.data[1]
11084
bar.y = [5, 3, 2, 8]
11185
```
11286

11387
```python
114-
import plotly.graph_objects as go
115-
f = go.FigureWidget()
116-
f.add_scatter(y=[2, 1, 4, 3])
117-
f.add_bar(y=[1, 4, 3, 2])
118-
f.layout.title = 'Hello FigureWidget'
119-
scatter = f.data[0]
120-
scatter.y = [3, 1, 4, 3]
121-
bar = f.data[1]
122-
bar.y = [5, 3, 2, 8]
123-
12488
f.layout.title.text = 'This is a new title'
12589
```
12690

@@ -150,7 +114,5 @@ f2
150114
See [these Jupyter notebooks](https://github.com/jonmmease/plotly_ipywidget_notebooks) for even more FigureWidget examples.
151115

152116
```python
153-
import plotly.graph_objects as go
154-
155117
help(go.FigureWidget)
156118
```

doc/python/network-graphs.md

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,8 @@ G = nx.random_geometric_graph(200, 0.125)
5757
Add edges as disconnected lines in a single trace and nodes as a scatter trace
5858

5959
```python
60-
import plotly.graph_objects as go
61-
import networkx as nx
62-
63-
G = nx.random_geometric_graph(200, 0.125)
6460
edge_x = []
6561
edge_y = []
66-
6762
for edge in G.edges():
6863
x0, y0 = G.nodes[edge[0]]['pos']
6964
x1, y1 = G.nodes[edge[1]]['pos']
@@ -120,16 +115,11 @@ Another option would be to size points by the number of connections
120115
i.e. ```node_trace.marker.size = node_adjacencies```
121116

122117
```python
123-
import networkx as nx
124-
125-
G = nx.random_geometric_graph(200, 0.125)
126118
node_adjacencies = []
127119
node_text = []
128-
129120
for node, adjacencies in enumerate(G.adjacency()):
130121
node_adjacencies.append(len(adjacencies[1]))
131122
node_text.append('# of connections: '+str(len(adjacencies[1])))
132-
133123
node_trace.marker.color = node_adjacencies
134124
node_trace.text = node_text
135125
```

doc/python/px-arguments.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,6 @@ df.head()
5555
By default `px.data` functions return a pandas `DataFrame` object, but you can specify an alternative dataframe type using `return_type`. `pandas`, `polars`, `pyarrow`, `modin`, and `cuDF` are supported return types.
5656

5757
```python
58-
import plotly.express as px
59-
6058
df = px.data.iris(return_type='polars')
6159
df.head()
6260
```

doc/python/static-image-export.md

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -204,23 +204,13 @@ Here's the bytes object displayed using `IPython.display.Image`:
204204

205205
```python
206206
from IPython.display import Image
207-
import plotly.express as px
208-
data_canada = px.data.gapminder().query("country == 'Canada'")
209-
fig = px.bar(data_canada, x='year', y='pop')
210-
img_bytes = fig.to_image(format="png")
211-
212207
Image(img_bytes)
213208
```
214209

215210
## Specify Image Dimensions and Scale
216211
In addition to the image format, the `to_image` and `write_image` functions provide arguments to specify the image `width` and `height` in logical pixels. They also provide a `scale` parameter that can be used to increase (`scale` > 1) or decrease (`scale` < 1) the physical resolution of the resulting image.
217212

218213
```python
219-
from IPython.display import Image
220-
import plotly.express as px
221-
data_canada = px.data.gapminder().query("country == 'Canada'")
222-
fig = px.bar(data_canada, x='year', y='pop')
223-
224214
img_bytes = fig.to_image(format="png", width=600, height=350, scale=2)
225215
Image(img_bytes)
226216
```

doc/python/ternary-contour.md

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,6 @@ fig.show()
128128
Two modes are available in order to interpolate between data points: interpolation in Cartesian space (`interp_mode='cartesian'`) or interpolation using the [isometric log-ratio transformation](https://link.springer.com/article/10.1023/A:1023818214614) (see also [preprint](https://www.researchgate.net/profile/Leon_Parent2/post/What_is_the_best_approach_for_diagnosing_nutrient_disorders_and_formulating_fertilizer_recommendations/attachment/59d62a69c49f478072e9cf3f/AS%3A272541220835360%401441990298625/download/Egozcue+et+al+2003.pdf)), `interp_mode='ilr'`. The `ilr` transformation preserves metrics in the [simplex](https://en.wikipedia.org/wiki/Simplex) but is not defined on its edges.
129129

130130
```python
131-
import numpy as np
132-
import plotly.figure_factory as ff
133-
134131
a, b = np.mgrid[0:1:20j, 0:1:20j]
135132
mask = a + b <= 1
136133
a, b = a[mask], b[mask]
@@ -141,9 +138,6 @@ fig.show()
141138
```
142139

143140
```python
144-
import numpy as np
145-
import plotly.figure_factory as ff
146-
147141
a, b = np.mgrid[0:1:20j, 0:1:20j]
148142
mask = a + b <= 1
149143
a, b = a[mask], b[mask]

doc/python/ternary-scatter-contour.md

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,6 @@ print(clean_data({'L1': ['.03 0.5 0.47','0.4 0.5 0.1']}))
7070

7171
```python
7272
import plotly.graph_objects as go
73-
import pandas as pd
74-
75-
scatter_raw_data = pd.read_json('https://raw.githubusercontent.com/plotly/datasets/master/scatter_data.json')
76-
scatter_data = scatter_raw_data['Data']
7773

7874
a_list = []
7975
b_list = []
@@ -117,9 +113,7 @@ fig.show()
117113

118114
```python
119115
import plotly.graph_objects as go
120-
import pandas as pd
121116

122-
contour_raw_data = pd.read_json('https://raw.githubusercontent.com/plotly/datasets/master/contour_data.json')
123117
contour_dict = contour_raw_data['Data']
124118

125119
# Defining a colormap:

0 commit comments

Comments
 (0)