Monday 30 December 2019

django mpld3 multiple plots on a html page



#mpld/views

from django.http import  HttpResponse
from django.shortcuts import render
import matplotlib.pyplot as plt
from mpld3 import plugins, fig_to_html, save_html, fig_to_dict
import json
import numpy as np

#for numpy array is not json serializable error
class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

def index(request):
    fig1, ax1 = plt.subplots()
    np.random.seed(0)
    x1, y1 = np.random.normal(size=(2, 200))
    color, size = np.random.random((2, 200))

    ax1.scatter(x1, y1, c=color, s=500 * size, alpha=0.3)
    ax1.grid(color='lightgray', alpha=0.7)

    fig2, ax2 = plt.subplots(3, 3, figsize=(6, 6))
    fig2.subplots_adjust(hspace=0.1, wspace=0.1)
    ax2 = ax2[::-1]

    X2 = np.random.normal(size=(3, 100))
    for i in range(3):
        for j in range(3):
            ax2[i, j].xaxis.set_major_formatter(plt.NullFormatter())
            ax2[i, j].yaxis.set_major_formatter(plt.NullFormatter())
            points = ax2[i, j].scatter(X2[j], X2[i])

    plugins.connect(fig2, plugins.LinkedBrush(points))

    fig3, ax3 = plt.subplots()
    x3 = np.linspace(-5, 15, 1000)
    for offset in np.linspace(0, 3, 4):
        ax3.plot(x3, 0.9 * np.sin(x3 - offset), lw=5, alpha=0.4,
                label="Offset: {0}".format(offset))
    ax3.set_xlim(0, 10)
    ax3.set_ylim(-1.2, 1.0)
    ax3.text(5, -1.1, "Here are some curves", size=18, ha='center')
    ax3.grid(color='lightgray', alpha=0.7)
    ax3.legend()

    fig4, ax4 = plt.subplots(2, 2, figsize=(8, 6), sharex='col', sharey='row')
    fig4.subplots_adjust(hspace=0.3)

    np.random.seed(0)

    for axi in ax4.flat:
        color = np.random.random(3)
        axi.plot(np.random.random(30), lw=2, c=color)
        axi.set_title("RGB = ({0:.2f}, {1:.2f}, {2:.2f})".format(*color),
                      size=14)
        axi.grid(color='lightgray', alpha=0.7)

    #save_html(fig, 'fig.html')
    g1 = json.dumps(fig_to_dict(fig1), cls=NumpyEncoder)
    g2 = json.dumps(fig_to_dict(fig2), cls=NumpyEncoder)
    g3 = json.dumps(fig_to_dict(fig3))
    g4 = json.dumps(fig_to_dict(fig4))


    return render(request, 'mpld/index.html',
                  {'graph1': g1,
                   'graph2': g2,
                   'graph3': g3,
                   'graph4': g4})

--------------------------------
#mpld/templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MPLD3</title>
    <!--bootstrap-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</head>
<body>
     <!--mpld3 script-->
    <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
    <script type="text/javascript" src="http://mpld3.github.io/js/mpld3.v0.2.js"></script>
    <div class="row">
        <div class="col">
            <div id="fig1">graph1</div>
        </div>
        <div class="col">
            <div id="fig2">graph2</div>
        </div>
        <div class="col">
            <div id="fig3">graph3</div>
        </div>
        <div class="col">
            <div id="fig4">graph4</div>
        </div>
    </div>

    <script type="text/javascript">
        mpld3.draw_figure("fig1", {{graph1 | safe}});
        mpld3.draw_figure("fig2", {{graph2 | safe}});
        mpld3.draw_figure("fig3", {{graph3 | safe}});
        mpld3.draw_figure("fig4", {{graph4 | safe}});
</script>
</body>
</html>

-----------------------------
#django_mpld3/settings

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR, 'mpld' , 'templates')],
        ...
    },
]

reference:
https://github.com/mpld3/mpld3/issues/128
https://stackoverflow.com/questions/22981359/display-multiple-mpld3-exports-on-a-single-html-page/
https://stackoverflow.com/questions/31151229/django-passing-json-from-view-to-template
https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable
https://mpld3.github.io/notebooks/mpld3_demo.html

No comments:

Post a Comment