Skip to content

Instantly share code, notes, and snippets.

@Matjaz-B
Last active July 5, 2023 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Matjaz-B/e6cc46dddbd625060e8011948488e79a to your computer and use it in GitHub Desktop.
Save Matjaz-B/e6cc46dddbd625060e8011948488e79a to your computer and use it in GitHub Desktop.
Plot multiple plots on same html using mpld3
import numpy as np
import matplotlib.pyplot as plt
import plotly.tools as tls
import json
import jinja2
template_str = """<!Doctype Html>
<html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
{% for plot in dict_of_plots %}
<div id="plt_{{ plot['id'] }}"></div>
<script>
var plot_{{ plot['id'] }} = {{ plot['json'] }};
Plotly.newPlot('plt_{{ plot['id'] | safe}}', plot_{{ plot['id'] | safe}});
</script>
{% endfor %}
</body>
</html>
"""
environment = jinja2.Environment()
template = environment.from_string(template_str)
dict_of_plots = list()
for i in range(5):
fig, ax = plt.subplots(1,1)
ax.plot(np.random.random(100), np.random.random(100), label=f"plot {i}")
single_chart = dict()
single_chart['id'] = i
# Convert Matplotlib graph to Plotly
plotly_fig = tls.mpl_to_plotly(fig)
plotly_fig['layout']['showlegend'] = True
single_chart['json'] = json.dumps(plotly_fig.to_dict())
dict_of_plots.append(single_chart)
html = template.render(dict_of_plots=dict_of_plots)
with open("test.html", 'w') as f:
f.write(html)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
reference https://github.com/mpld3/mpld3/issues/128
"""
import matplotlib.pyplot as plt
import mpld3
import numpy as np
import jinja2
from json import dumps
template_str = """
<html>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript" src="https://mpld3.github.io/js/mpld3.v0.5.9.js"></script>
<head>
</head>
<body>
{% for plot in dict_of_plots %}
<div id="plt_{{ plot['id'] }}"></div>
{% endfor %}
<script type="text/javascript">
{% for plot in dict_of_plots %}
mpld3.draw_figure("plt_{{ plot['id'] }}", {{ plot['json']|safe }});
{% endfor %}
</script>
</body>
</html>
"""
environment = jinja2.Environment()
template = environment.from_string(template_str)
# Define a function that will return an HTML snippet.
def build_plot():
x_deets = np.random.random(10_000)
y_deets = np.random.random(10_000)
fig, ax = plt.subplots(1,1, figsize=(15,10))
ax.plot(x_deets, y_deets, 'rx', label="plot")
ax.legend()
# indata = pd.DataFrame(x_deets, y_deets,)
# indata.plot(ax=ax, )
output = dumps(mpld3.fig_to_dict(fig))
return output
def render_plot():
sample_list = list(np.random.randint(1,199,size=2))
dict_of_plots = list()
for i in sample_list:
single_chart = dict()
single_chart['id'] = i
single_chart['json'] = build_plot()
dict_of_plots.append(single_chart)
return template.render(dict_of_plots=dict_of_plots)#snippet=plot_snippet)
with open("test.html", 'w') as f:
f.write(render_plot())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment