Skip to content

Commit 1805f01

Browse files
authored
Merge pull request #224 from lucasimi/embedded-rendering-streamlit
Added embedded rendering of plotly figure to prevent view reset
2 parents 2f534fe + 859a38d commit 1805f01

File tree

1 file changed

+55
-8
lines changed

1 file changed

+55
-8
lines changed

app/streamlit_app.py

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import numpy as np
1111
import pandas as pd
1212
import streamlit as st
13+
import streamlit.components.v1 as components
14+
from jinja2 import Template
1315
from networkx.readwrite.json_graph import adjacency_data
1416
from sklearn.cluster import (
1517
DBSCAN,
@@ -133,6 +135,36 @@
133135
f":star: on **[GitHub]({GIT_REPO_URL})**."
134136
)
135137

138+
EMBEDDED_RENDERING = True
139+
140+
PLOTLY_TEMPLATE = Template(
141+
"""
142+
<!DOCTYPE html>
143+
<html>
144+
<style>
145+
html, body {
146+
margin: 0;
147+
padding: 0;
148+
height: 100%;
149+
width: 100%;
150+
}
151+
.plot-container {
152+
height: 100%;
153+
width: 100%;
154+
}
155+
</style>
156+
<head>
157+
<meta charset="utf-8" />
158+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
159+
</head>
160+
<body>
161+
<div class="plot-container">
162+
{{ fig | safe }}
163+
<div>
164+
</body>
165+
</html>
166+
"""
167+
)
136168

137169
logger = st.logger.get_logger(__name__)
138170

@@ -777,14 +809,29 @@ def _edge_colors(mapper_plot, df_X, df_y, col_feat, agg):
777809

778810

779811
def mapper_rendering_section(mapper_fig):
780-
config = {
781-
"scrollZoom": True,
782-
"displaylogo": False,
783-
"modeBarButtonsToRemove": ["zoom", "pan"],
784-
}
785-
st.plotly_chart(
786-
mapper_fig, use_container_width=True, config=config, key="mapper_plot"
787-
)
812+
if EMBEDDED_RENDERING:
813+
mapper_fig.layout.width = None
814+
mapper_fig.layout.autosize = True
815+
fig_html = mapper_fig.to_html(
816+
full_html=False,
817+
include_plotlyjs="cdn",
818+
config={"responsive": True},
819+
)
820+
rendered_html = PLOTLY_TEMPLATE.render(fig=fig_html)
821+
height = mapper_fig.layout.height
822+
components.html(rendered_html, height=height)
823+
else:
824+
config = {
825+
"scrollZoom": True,
826+
"displaylogo": False,
827+
"modeBarButtonsToRemove": ["zoom", "pan"],
828+
}
829+
st.plotly_chart(
830+
mapper_fig,
831+
use_container_width=True,
832+
config=config,
833+
key="mapper_plot",
834+
)
788835

789836

790837
def data_summary_section(df_X, df_y, mapper_graph):

0 commit comments

Comments
 (0)