Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

adding a JavaScript/Jinja example to dropdowns.md #4886

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
LiamConnors merged 11 commits into plotly:doc-prod from rl-utility-man:patch-8
Dec 16, 2024
Merged
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
adding a JavaScript/Jinja example to dropdowns.md
  • Loading branch information
rl-utility-man authored Nov 18, 2024
commit 05e84851cbc5b8151d51aebf2264d9034b4babce
89 changes: 89 additions & 0 deletions doc/python/dropdowns.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -444,5 +444,94 @@ fig.update_layout(title_text="Yahoo")
fig.show()
```

### Creating several independent graphs and using Jinja to insert them into a JavaScript enabled webpage
Copy link
Member

@LiamConnors LiamConnors Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
### Creating several independent graphs and using Jinja to insert them into a JavaScript enabled webpage
### Embedding Multiple Graphs in a Webpage using Jinja

We can shorten this if possible, so it takes up less space on the left sidebar

Copy link
Contributor Author

@rl-utility-man rl-utility-man Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good suggestion. What would you think of "Using a Dropdown to Select a Graph Using Jinja" as a short title?

LiamConnors reacted with thumbs up emoji

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).

#### Python Code File

```
import plotly.express as px
from jinja2 import Template
Copy link
Member

@LiamConnors LiamConnors Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this needs to be marked as a python block.
Right now it's rendering as text:
image

Copy link
Contributor Author

@rl-utility-man rl-utility-man Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed! Thanks!

Copy link
Member

@LiamConnors LiamConnors Dec 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This probably actually needs the same <!-- #region --> blocks as well as being marked as Python, as in:

https://github.com/plotly/plotly.py/blob/doc-prod/doc/python/interactive-html-export.md?plain=1#L59-L102

Copy link
Contributor Author

@rl-utility-man rl-utility-man Dec 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in commit 5; there's something funky with the preview screen -- neither the example -- which demonstrably renders correctly when live -- nor my new commit convert e.g. > to > in preview mode. I hope I've done everything right, but it's difficult to tell.

import collections
# Load the gapminder dataset
df = px.data.gapminder()

#create a dictionary with Plotly figures as values
fig_dict = {}

# Loop through each unique continent and create a scatter plot using the 2007 data
for continent in df['continent'].unique():
# Filter data for the current continent
continent_data = df[(df['continent'] == continent) & (df['year'] == 2007)]

fig_dict[continent] = px.scatter(continent_data, x='gdpPercap', y='lifeExp',
title=f'GDP vs Life Expectancy for {continent}',
labels={'gdpPercap': 'GDP per Capita (USD)', 'lifeExp': 'Life Expectancy (Years)'},
hover_name='country',
)

# Create a dictionary, data_for_jinja with two entries:
# the value for the "dropdown_entries" key contains string containing a series of <option> tags, one for each item in the drop down
# 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
# in this example, that content is a figure and descriptive text.
data_for_jinja= collections.defaultdict(str)
text_dict = {}
for n, figname in enumerate(fig_dict.keys()):
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
data_for_jinja["dropdown_entries"]+=f"<option value='{figname}'>{fig_dict[figname].layout.title.text}</option>"
#YOU MAY NEED TO UPDATE THE LINK TO THE LATEST PLOTLY.JS
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")
data_for_jinja["divs"]+=f'<div id="{figname}" class="content-div" {"style=""display:none;"""*(n>0)}>{fig_html}{text_dict[figname]}</div>'

# Insert data into the template and write the file to disk
# YOU WILL LIKELY NEED TO CUSTOMIZE THESE PATHS
input_template_path=r"C:\data\demo_template.jinja"
output_html_path=r"C:\data\demo_result.html"

with open(output_html_path, "w", encoding='utf-8') as output_file:
with open(input_template_path) as template_file:
j2_template = Template(template_file.read())
output_file.write(j2_template.render(data_for_jinja))
```

#### Jinja HTML Template

```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

</head>
Copy link
Member

@LiamConnors LiamConnors Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not certain why, but this renders like this in the generated page. We probably want to mark it as txt. Do you edit the files in a Jupyter notebook or the md file directly

image

Copy link
Contributor Author

@rl-utility-man rl-utility-man Dec 2, 2024
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for all these good edits. I edited the .md directly. There's an example of embedding HTML into the .md here: https://plotly.com/python/interactive-html-export/

The gist of it is to use e.g. lt; rather than <:

<!-- #region -->
[three backticks]
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

I can make the requisite edits in the next day or two

Copy link
Contributor Author

@rl-utility-man rl-utility-man Dec 3, 2024
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just committed changes that resolve this problem. The preview now looks good to me. Thank you for flagging this!

<body>
<div class="container">
<h1>Select an analysis</h1>
<select id="dropdown" class="form-control">
{{ dropdown_entries }}
</select>


{{ divs }}

</div>

<script>
document.getElementById('dropdown').addEventListener('change', function() {
const divs = document.querySelectorAll('.content-div');
divs.forEach(div => div.style.display = 'none');

const selectedDiv = document.getElementById(this.value);
if (selectedDiv) {
selectedDiv.style.display = 'block';
}
});
</script>
</body>
</html>
```



#### Reference
See https://plotly.com/python/reference/layout/updatemenus/ for more information about `updatemenu` dropdowns.

AltStyle によって変換されたページ (->オリジナル) /