如何在matplotlib中将图添加到图中?

时间:2010-12-27 12:45:29

标签: django matplotlib

我正在使用matjlotlib和django。我正在尝试制作条形图。

我跟着cookbook,但我得到一个灰色的矩形框。

现在我正在使用以下代码,并且有一个标题和轴。

如何在图中添加条形图?目前轴内没有实际数据。

这是我的图表代码:

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

在我看来,我有:

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 个答案:

答案 0 :(得分: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)

这将创建一个条形图,并保存图像。只需将该功能调用到您的视图中即可。并在模板中打开图像。我把字典传给了这个函数(dic),但你可以传递一个列表,由你决定。

在这种情况下,键是x轴,值是y轴。