Skip to content

Commit 05e8485

Browse files
adding a JavaScript/Jinja example to dropdowns.md
1 parent 193a4b7 commit 05e8485

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

Diff for: doc/python/dropdowns.md

+89
Original file line numberDiff line numberDiff line change
@@ -444,5 +444,94 @@ fig.update_layout(title_text="Yahoo")
444444
fig.show()
445445
```
446446

447+
### Creating several independent graphs and using Jinja to insert them into a JavaScript enabled webpage
448+
449+
It is often easier to create each potential view as a separate graph and then use Jinja to insert each potential view into a div on a JavaScript enabled webpage with a drop down that chooses which div to display. This approach produces code that requires little customization or updating as you e.g. add, drop, or reorder views or traces, so it is particularly compelling for prototyping and rapid iteration. This requires both a Python program and a Jinja template file. You may want to consult the documentation on [using Jinja templates with Plotly](https://plotly.com/python/interactive-html-export/#inserting-plotly-output-into-html-using-a-jinja2-template).
450+
451+
#### Python Code File
452+
453+
```
454+
import plotly.express as px
455+
from jinja2 import Template
456+
import collections
457+
# Load the gapminder dataset
458+
df = px.data.gapminder()
459+
460+
#create a dictionary with Plotly figures as values
461+
fig_dict = {}
462+
463+
# Loop through each unique continent and create a scatter plot using the 2007 data
464+
for continent in df['continent'].unique():
465+
# Filter data for the current continent
466+
continent_data = df[(df['continent'] == continent) & (df['year'] == 2007)]
467+
468+
fig_dict[continent] = px.scatter(continent_data, x='gdpPercap', y='lifeExp',
469+
title=f'GDP vs Life Expectancy for {continent}',
470+
labels={'gdpPercap': 'GDP per Capita (USD)', 'lifeExp': 'Life Expectancy (Years)'},
471+
hover_name='country',
472+
)
473+
474+
# Create a dictionary, data_for_jinja with two entries:
475+
# the value for the "dropdown_entries" key contains string containing a series of <option> tags, one for each item in the drop down
476+
# the value for the "divs" key contains a string with a series of <div> tags, each containing the content that appears only when the user selects the corresponding item from the dropdown
477+
# in this example, that content is a figure and descriptive text.
478+
data_for_jinja= collections.defaultdict(str)
479+
text_dict = {}
480+
for n, figname in enumerate(fig_dict.keys()):
481+
text_dict[figname]=f"Here is some custom text about the {figname} figure" #This is a succinct way to populate text_dict; in practice you'd probably populate it manually elsewhere
482+
data_for_jinja["dropdown_entries"]+=f"<option value='{figname}'>{fig_dict[figname].layout.title.text}</option>"
483+
#YOU MAY NEED TO UPDATE THE LINK TO THE LATEST PLOTLY.JS
484+
fig_html = fig_dict[figname].to_html(full_html=False, config=dict(responsive=False, scrollZoom=False, doubleClick=False), include_plotlyjs = "https://cdn.plot.ly/plotly-2.35.2.min.js")
485+
data_for_jinja["divs"]+=f'<div id="{figname}" class="content-div" {"style=""display:none;"""*(n>0)}>{fig_html}{text_dict[figname]}</div>'
486+
487+
# Insert data into the template and write the file to disk
488+
# YOU WILL LIKELY NEED TO CUSTOMIZE THESE PATHS
489+
input_template_path=r"C:\data\demo_template.jinja"
490+
output_html_path=r"C:\data\demo_result.html"
491+
492+
with open(output_html_path, "w", encoding='utf-8') as output_file:
493+
with open(input_template_path) as template_file:
494+
j2_template = Template(template_file.read())
495+
output_file.write(j2_template.render(data_for_jinja))
496+
```
497+
498+
#### Jinja HTML Template
499+
500+
```
501+
<!DOCTYPE html>
502+
<html lang="en">
503+
<head>
504+
<meta charset="UTF-8">
505+
506+
</head>
507+
<body>
508+
<div class="container">
509+
<h1>Select an analysis</h1>
510+
<select id="dropdown" class="form-control">
511+
{{ dropdown_entries }}
512+
</select>
513+
514+
515+
{{ divs }}
516+
517+
</div>
518+
519+
<script>
520+
document.getElementById('dropdown').addEventListener('change', function() {
521+
const divs = document.querySelectorAll('.content-div');
522+
divs.forEach(div => div.style.display = 'none');
523+
524+
const selectedDiv = document.getElementById(this.value);
525+
if (selectedDiv) {
526+
selectedDiv.style.display = 'block';
527+
}
528+
});
529+
</script>
530+
</body>
531+
</html>
532+
```
533+
534+
535+
447536
#### Reference
448537
See https://plotly.com/python/reference/layout/updatemenus/ for more information about `updatemenu` dropdowns.

0 commit comments

Comments
 (0)