Skip to content

Commit 861b421

Browse files
authored
Merge pull request #4886 from rl-utility-man/patch-8
adding a JavaScript/Jinja example to dropdowns.md
2 parents 6f22731 + 8e9c21a commit 861b421

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

Diff for: doc/python/dropdowns.md

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

447+
### Graph Selection Dropdowns in Jinja
448+
449+
It is straight forward 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 dropdown 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. It produces web pages that are larger than the webpages produced through the built in method which is a consideration for very large figures with hundreds or thousands of data points in traces that appear in multiple selections. This approach requires both a Python program and a Jinja template file. The documentation on [using Jinja templates with Plotly](https://plotly.com/python/interactive-html-export/#inserting-plotly-output-into-html-using-a-jinja2-template) is relevant background.
450+
451+
<!-- #region -->
452+
453+
#### Python Code File
454+
455+
```python
456+
import plotly.express as px
457+
from jinja2 import Template
458+
import collections
459+
# Load the gapminder dataset
460+
df = px.data.gapminder()
461+
462+
# Create a dictionary with Plotly figures as values
463+
fig_dict = {}
464+
465+
# we need to fill that dictionary with figures. this example assumes that each figure has a title and that
466+
# we want to use the titles as descriptions in the drop down
467+
# This example happens to fill the dictionary by creating a scatter plot for each continent using the 2007 Gapminder data
468+
for continent in df['continent'].unique():
469+
# Filter data for the current continent
470+
continent_data = df[(df['continent'] == continent) & (df['year'] == 2007)]
471+
472+
fig_dict[continent] = px.scatter(continent_data, x='gdpPercap', y='lifeExp',
473+
title=f'GDP vs Life Expectancy for {continent}',
474+
labels={'gdpPercap': 'GDP per Capita (USD)', 'lifeExp': 'Life Expectancy (Years)'},
475+
hover_name='country',size="pop", size_max=55
476+
)
477+
#Standardizing the axes makes the graphs easier to compare
478+
fig_dict[continent].update_xaxes(range=[0,50000])
479+
fig_dict[continent].update_yaxes(range=[25,90])
480+
481+
482+
# Create a dictionary, data_for_jinja with two entries:
483+
# the value for the "dropdown_entries" key is a string containing a series of <option> tags, one tag for each item in the drop down
484+
# the value for the "divs" key is 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
485+
# in this example, the content of each div is a figure and descriptive text.
486+
data_for_jinja= collections.defaultdict(str)
487+
text_dict = {}
488+
for n, figname in enumerate(fig_dict.keys()):
489+
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
490+
data_for_jinja["dropdown_entries"]+=f"<option value='{figname}'>{fig_dict[figname].layout.title.text}</option>"
491+
#YOU MAY NEED TO UPDATE THE LINK TO THE LATEST PLOTLY.JS
492+
fig_html = fig_dict[figname].to_html(full_html=False, config=dict(responsive=False, scrollZoom=False, doubleClick=False), include_plotlyjs = "cdn")
493+
initially_hide_divs_other_than_the_first = "style=""display:none;"""*(n>0)
494+
data_for_jinja["divs"]+=f'<div id="{figname}" class="content-div" {initially_hide_divs_other_than_the_first}>{fig_html}{text_dict[figname]}</div>'
495+
496+
# Insert data into the template and write the file to disk
497+
# You'll need to add the path to your template and to your preferred output location
498+
input_template_path=r"<path-to-Jinja-template.html>"
499+
output_html_path=r"<path-to-output-file.html>"
500+
501+
with open(output_html_path, "w", encoding='utf-8') as output_file:
502+
with open(input_template_path) as template_file:
503+
j2_template = Template(template_file.read())
504+
output_file.write(j2_template.render(data_for_jinja))
505+
```
506+
507+
#### Jinja HTML Template
508+
509+
510+
```
511+
&lt;!DOCTYPE html&gt;
512+
&lt;html lang="en"&gt;
513+
&lt;head&gt;
514+
&lt;meta charset="UTF-8"&gt;
515+
516+
&lt;/head&gt;
517+
&lt;body&gt;
518+
&lt;div class="container"&gt;
519+
&lt;h1&gt;Select an analysis&lt;/h1&gt;
520+
&lt;select id="dropdown" class="form-control"&gt;
521+
{{ dropdown_entries }}
522+
&lt;/select&gt;
523+
524+
525+
{{ divs }}
526+
527+
&lt;/div&gt;
528+
529+
&lt;script&gt;
530+
document.getElementById('dropdown').addEventListener('change', function() {
531+
const divs = document.querySelectorAll('.content-div');
532+
divs.forEach(div =&gt; div.style.display = 'none');
533+
534+
const selectedDiv = document.getElementById(this.value);
535+
if (selectedDiv) {
536+
selectedDiv.style.display = 'block';
537+
}
538+
});
539+
&lt;/script&gt;
540+
&lt;/body&gt;
541+
&lt;/html&gt;
542+
```
543+
544+
<!-- #endregion -->
545+
447546
#### Reference
448547
See https://plotly.com/python/reference/layout/updatemenus/ for more information about `updatemenu` dropdowns.

0 commit comments

Comments
 (0)