Monday, May 15, 2017

[Mpld3] Render Matplotlib chart to web using Mpld3

The following example is about rendering a matplotlib chart on web, which is based on Django framework to build up. I encountered some problems before, such as, not able to see chart on the web page or having a run-time error after reloading the page. But, all the problems are solved.

<< demo/>>

import matplotlib.pyplot as plt
import numpy as np
import mpld3

def plot_test1(request):
context = {}
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

Demo about using matplotlib and mpld3 to rendor charts
scatter = ax.scatter(np.random.normal(size=N),
s=1000 * np.random.random(size=N),
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)
#figure = mpld3.fig_to_html(fig)
figure = json.dumps(mpld3.fig_to_dict(fig))
context.update({ 'figure' : figure })

Demo about using tensorflow to predict the result
num = np.random.randint(100)
prediction = predict_service.predict(num)
context.update({ 'num' : num })
context.update({ 'prediction' : prediction })

return render(request, 'demo/demo.html', context)


<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
/* Move down content because we have a fixed navbar that is 50px tall */
body {
padding-top: 50px;
padding-bottom: 20px;
<div id="fig01"></div>
<script type="text/javascript">

figure = {{ figure|safe }};
mpld3.draw_figure("fig01", figure);


So, we can see the result as follows:

Post a Comment