2

i'm using matplotlib with django. I'm trying to create bar charts.

i followed the cookbook, but i just got a grey rectangular box.

Now I'm using the following code, and have a title and axes.

How can I add a bar graph to the figure? Currently there is no actual data inside the axes.

Here's my charting code:

from matplotlib.backends.backend_agg import FigureCanvasAgg 
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

class Chart(object):

    ## Creates a bar chart of the given data
    @staticmethod
    def bar(data):
        figure = Figure(figsize=(6,6))
        ax = figure.add_axes([0.1, 0.1, 0.8, 0.8])
        labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
        fracs = [15, 30, 45, 10]
        explode=(0, 0.05, 0, 0)
        plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
        figure.suptitle('Raining Hogs and Dogs', fontsize=14)

        canvas = FigureCanvasAgg(figure)

        return canvas

In my view I have:

canvas = Chart.bar(results)

# turn the returned canvas into an HTTP response
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
return response

1 Answer 1

8
    fig = Figure()
    fig = Figure(facecolor='white', edgecolor='white')
    ax = fig.add_subplot(1,1,1)

    x = matplotlib.numpy.arange(0, len(dic.keys()))

    ind = matplotlib.numpy.arange(len(dic.values()))

    height = 0.8
    ax.bar(ind, dic.values(), width, color=colors)

    ax.set_xticks(ind + width / 2.0)
    ax.set_xticklabels(dic.keys())

    padding = 0.2
    ax.set_xlim([x.min() - padding, x.max() + width + padding])

    canvas =  FigureCanvas(fig)
    response = django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    fig.savefig(filename)

this will create a bar graph, and save the image. Just have to call the function into your views. and open the image in the template. I passed a dictionary to this function(dic) but you can pass a list, is up to you.

in this case the keys are the x axis and the values are the y axis.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.