Skip to content

Commit 9121132

Browse files
author
siranipour
committed
Saving plotly figures for interactive plots
1 parent 4d2bb91 commit 9121132

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/reportengine/environment.py

+3
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ def init_output(self):
113113
self.table_folder = (self.output_path/'tables')
114114
self.table_folder.mkdir(exist_ok=True)
115115

116+
def get_interactive_figure_paths(self, handle):
117+
yield self.figure_folder / (handle + '.html')
118+
116119
def get_figure_paths(self, handle):
117120
for fmt in self.figure_formats:
118121
yield self.figure_folder / (handle + '.' + fmt)

src/reportengine/figure.py

+40
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,41 @@ def as_markdown(self):
5353
retmd = f'![{links}]({self.paths[0]}){{{anchor_link_target}}} \n'
5454
return retmd
5555

56+
class InteractiveFigure():
57+
def __init__(self, paths, graph_obj):
58+
self.paths = paths
59+
self.graph_obj = graph_obj
60+
61+
@property
62+
def as_markdown(self):
63+
# Prepare the anchor
64+
anchor_link_target = f'#{self.paths[0].stem}'
65+
# Prepare the link to the actual figures
66+
plot = self.graph_obj.to_html(include_plotlyjs='cdn', full_html=False)
67+
plot = ' '.join(plot.split())
68+
links = ' '.join(_generate_markdown_link(path) for path in self.paths) + ' '
69+
links += _generate_markdown_link(anchor_link_target, "#")
70+
# https://stackoverflow.com/questions/14051715/markdown-native-text-alignment#comment60291976_19938870
71+
retmd = f'{plot}\n <p style="text-align: center;">{links}</p>\n'
72+
return retmd
73+
74+
def saveinteractivefig(fig, *, paths, output, suffix=''):
75+
"""Save a plotly figure as html for interactive plots
76+
"""
77+
outpaths = []
78+
for path in paths:
79+
if suffix:
80+
suffix = normalize_name(suffix)
81+
path = path.with_name('_'.join((path.stem, suffix)) + path.suffix)
82+
fig.write_html(path, include_plotlyjs='cdn')
83+
outpaths.append(path.relative_to(output))
84+
return InteractiveFigure(outpaths, fig)
85+
86+
87+
def prepare_interactive_paths(*, spec, namespace, environment, **kwargs):
88+
paths = environment.get_interactive_figure_paths(spec_to_nice_name(namespace, spec))
89+
return {'paths': list(paths), 'output': environment.output_path}
90+
5691

5792
def prepare_paths(*,spec, namespace, environment ,**kwargs):
5893
paths = environment.get_figure_paths(spec_to_nice_name(namespace, spec))
@@ -107,6 +142,11 @@ def savefiglist(figures, paths, output):
107142
res.append("</div>")
108143
return res
109144

145+
@add_highlight
146+
def interactive_figure(f):
147+
f.prepare = prepare_interactive_paths
148+
f.final_action = saveinteractivefig
149+
return f
110150

111151
@add_highlight
112152
def figure(f):

0 commit comments

Comments
 (0)