如何为pyplot定义画布以便在HTML文档中绘图?

时间:2018-02-13 10:04:13

标签: python html django matplotlib canvas

我正在使用Django制作网页。我尝试使用matplotlib创建的条形图出现在我的网页上,但收到以下错误消息,说我没有定义属性'canvas':

Traceback:

File "C:\Python3.6\lib\site-packages\django\core\handlers\exception.py" in inner
  35.   response = get_response(request)

File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.  response = self.process_exception_by_middleware(e, request)

File "C:\Python3.6\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.  response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\JNPou\Desktop\Den bæredygtige back-up\kogebog\opskriftssoegning\views.py" in Opskriftsside
  136.  json1 = json.dumps(mpld3.fig_to_dict(bar_plot))

File "C:\Python3.6\lib\site-packages\mpld3\_display.py" in fig_to_dict
  167.  Exporter(renderer, close_mpl=False, **kwargs).run(fig)

File "C:\Python3.6\lib\site-packages\mpld3\mplexporter\exporter.py" in run
  45.   if fig.canvas is None:

Exception Type: AttributeError at /opskriftssoegning/kartoffelsuppe-med-porrer/
Exception Value: 'tuple' object has no attribute 'canvas'

这是我创建剧情的Python代码:

import matplotlib
matplotlib.use('Agg')

import json
import numpy as np
import matplotlib.pyplot as plt, mpld3
import pandas as pd

[...]

def make_bar_plot():
    height = [1, 2, 3, 3.33, 3.67, 4, 4.33, 4.67, 5, 6, 7, 8, 9, 10, 11, 11.33, 11.67, 12, 12.33, 12.67, 13, 14, 15]
    bars = ('1','2','3','4','5','6','7','8','9','10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23')
    y_pos_prototype = np.arange(len(bars))
    y_pos = pd.Series(y_pos_prototype).to_json(orient='values')
    #y_pos = np.arange(len(bars))

    fig = plt.figure()

    color_set = red_yellow_green_gradient(height)
    # Create bars
    plt.bar(y_pos, height, color=color_set, figure=fig)

    # Create names on the x-axis
    plt.xticks(y_pos, bars, fontsize=16, figure=fig)

    # Add title and axis names
    plt.xlabel('categories', fontsize=18, figure=fig)
    plt.ylabel('values', fontsize=18, figure=fig)

    return fig

创建绘图后,我将其分配到Django视图中的字典:

import os

import json
import numpy as np

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt, mpld3

from .plots import red_yellow_green_gradient, make_bar_plot

[...]

def Opskriftsside(request,slug):
    [...]
    bar_plot = make_bar_plot()
    json1 = json.dumps(mpld3.fig_to_dict(bar_plot)) #THINGS GO WRONG HERE
    context['bar_plot']=bar_plot
    context['json1']=json1
    return render(request,'opskriftssoegning/opskrift.html',context)

最后,这是相关的HTML代码:

<div id="fig"></div>
    <script type="text/javascript">
      var json1 = { json.dumps(mpld3.fig_to_dict(fig)) };
      mpld3.draw_figure("fig", json1);
    </script>

我的问题是:如何为我的pyplot数字分配画布?

1 个答案:

答案 0 :(得分:0)

尝试使用mpl3

将pyplot图导出为html

fig_to_html() 要么 save_html() 然后用jason解析,然后将它添加到你从python

传递给html的上下文字典中

一些信息:https://mpld3.github.io/modules/API.html