Matplotlib into a Django Template
Question: 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!


Answer: Edit:

try with

    
    
    graphic = cStringIO.StringIO()
    canvas.print_png(graphic)
    return render(request, 'graphic.html',{'graphic':graphic})
    

You have to specify that your image is a binary string:

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

Or actually save it to the filesystem and provide the path.

Alternatively you could use bokeh <http://bokeh.pydata.org/en/latest/> which
can give you the html + javascript to embed the plot direclty in the template,
then it is dynamically generated and brings nice features.

It's built by continum analytics, the anaconda distro guys.

