Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib into a Django Template

Im using python 3.4 and Django 1.8. I want to "print" a matplotlib result in a Django template. I reach this a few days ago, so I continue in other things of my Django App. Now, I dont know why, I was going to show the result to a friend, and my template with a matplotlib graph, now shows a big code! I dont know why this happen, because my view doesnt change in anything from when it was showing the right graph! Please help me!

This is my view!

from django.shortcuts import render
from matplotlib import pylab
from pylab import *
import PIL
import PIL.Image
import io
from io import *

def graphic(request):

pos = arange(10)+ 2 

barh(pos,(1,2,3,4,5,6,7,8,9,10),align = 'center')

yticks(pos,('#hcsm','#ukmedlibs','#ImmunoChat','#HCLDR','#ICTD2015','#hpmglobal','#BRCA','#BCSM','#BTSM','#OTalk'))

xlabel('Popularity')
ylabel('Hashtags')
title('Hashtags')
subplots_adjust(left=0.21)

buffer = io.BytesIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
graphIMG = PIL.Image.fromstring('RGB', canvas.get_width_height(),               canvas.tostring_rgb())
graphIMG.save(buffer, "PNG")
content_type="Image/png"
buffercontent=buffer.getvalue()


graphic = (buffercontent ,content_type)
pylab.close()


return render(request, 'graphic.html',{'graphic':graphic})

Of course in my graphic.html is a variable called {{graphic}} inside a blockcontent!

This was showing the right result in my template! What happen? Now sometimes when i run my template it shows a big code, or just show me this django error:

Exception Value:
main thread is not in main loop

Exception Location: C:\Python34\lib\site-packages\matplotlib\backends\tkagg.py in blit, line 17

Help!

like image 514
Cesar Borge Mora Avatar asked May 29 '15 14:05

Cesar Borge Mora


1 Answers

    from io import BytesIO
    import base64
    import matplotlib.pyplot as plt
    import numpy as np

    def graphic(request):

        pos = np.arange(10)+ 2 

        fig = plt.figure(figsize=(8, 3))
        ax = fig.add_subplot(111)

        ax.barh(pos, np.arange(1, 11), align='center')
        ax.set_yticks(pos)
        ax.set_yticklabels(('#hcsm',
            '#ukmedlibs',
            '#ImmunoChat',
            '#HCLDR',
            '#ICTD2015',
            '#hpmglobal',
            '#BRCA',
            '#BCSM',
            '#BTSM',
            '#OTalk',), 
            fontsize=15)
        ax.set_xticks([])
        ax.invert_yaxis()

        ax.set_xlabel('Popularity')
        ax.set_ylabel('Hashtags')
        ax.set_title('Hashtags')

        plt.tight_layout()

        buffer = BytesIO()
        plt.savefig(buffer, format='png')
        buffer.seek(0)
        image_png = buffer.getvalue()
        buffer.close()

        graphic = base64.b64encode(image_png)
        graphic = graphic.decode('utf-8')

        return render(request, 'graphic.html',{'graphic':graphic})

and in the template:

<img src="data:image/png;base64,{{ graphic|safe }}">

I have:

matplotlib==3.0.2 and Django==2.1.4

like image 166
Pawel Piela Avatar answered Sep 21 '22 19:09

Pawel Piela