开发者

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 p开发者_StackOverflow中文版ng object?

sorry for this ...


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜