maksymov
maksymov

Reputation: 493

how to output horizontal barchart to django site page

I tried an examle in a django views.py:

import numpy as np
import matplotlib.pyplot as plt

N=3
Data = (1,2,9)
ind = np.arrange(N)
width = 0.35
p1 = plt.bar(ind, Data, width, color='r')

what i dont know - how to direc this to the page in django site. Shall i use plt.show() or try to create buffer for png object?

sorry for this ...

Upvotes: 0

Views: 2099

Answers (2)

Mario César
Mario César

Reputation: 3745

I have no tested that, but could work. You have to use the backend_agg for printing a canvas as png format, to be handle as a mimetype image/png file.

The better approach seems to be write a view to output the chars.

The view would be this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from django.http import HttpResponse

def bar_chart(request):
    if request.GET.get('data', False):
        data = (1,2,9)
    else:
        if type(request.GET['data']) == list():
            data = request.GET['data']

    chart = plt.bar(np.arange(3), data, 0.35, color='r')
    canvas = FigureCanvas(chart)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

# inside urls.py
#
# url(r'^charts/bar_chart.png$', 'myapp.views.charts.simple', name="bar_chart"),

And in your templates you can use this way:

<h1>My Bar Char</h1>
<img src="{% url bar_chart %}?data=[10,20,40,50,30,50]" />

This will render:

<h1>My Bar Char</h1>
<img src="/charts/bar_chart.png?data=[10,20,40,50,30,50]" />

I hope you can test it and complete this answer.

Upvotes: 1

Speccy
Speccy

Reputation: 694

This is what you are looking for :

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import matplotlib.pyplot as plt 
import django

def plot(request):
    plt.plot()
    canvas = FigureCanvas(plt.figure(1))
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

Upvotes: 2

Related Questions