问题
I'm trying to get a mpld3 chart into my webapp using Django and MPLD3/Matplotlib. As described here it should be straightforward getting the HTML code of the figure written in python.
Views.py
def figure(request):
np.random.seed(9615)
N = 100
df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0),
columns=['a', 'b', 'c', 'd', 'e'], )
# plot line + confidence interval
fig, ax = plt.subplots()
ax.grid(True, alpha=0.3)
for key, val in df.iteritems():
l, = ax.plot(val.index, val.values, label=key)
ax.fill_between(val.index,
val.values * .5, val.values * 1.5,
color=l.get_color(), alpha=.4)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Interactive legend', size=20)
html_fig = mpld3.fig_to_html(fig,template_type='general')
plt.close(fig)
return render(request, "dashboard.html", {'active_page' : 'dashboard.html', 'div_figure' : html_fig})
dashboard.html
<div id="fig_container">
{{ div_figure }}
</div>
AFAIK, the python code gets translated into javascript and should be executed when views.py is rendering dashboard.html, right?
As result, I get the HTML code displayed as text on my dashboard.hmtl.
QUESTION: How do I get the chart displayed? Do I need to parse the HTML string which is returned by the method html_to_fig?
回答1:
try this in the html
<div id="fig_container">
{{ div_figure|safe }}
</div>
来源:https://stackoverflow.com/questions/44924890/django-rendering-matplotlib-chart-in-html-using-mpld3