【问题标题】:Plot matplotlib on the Web在 Web 上绘制 matplotlib
【发布时间】:2011-07-27 18:45:26
【问题描述】:

下面的代码当然会创建一个名为 test 的 PNG 并保存在服务器上:

from matplotlib.figure import Figure                         
from matplotlib.backends.backend_agg import FigureCanvasAgg  

fig = Figure(figsize=[4,4])                                  
ax = fig.add_axes([.1,.1,.8,.8])                             
ax.scatter([1,2], [3,4])                                     
canvas = FigureCanvasAgg(fig)                                
canvas.print_figure("test.png")

然后要在浏览器中查看图像,我们必须转到 example.com/test.png。这意味着我们必须先用 Python 代码调用页面来创建 test.png 文件,然后转到 PNG 文件。有没有办法从创建图像的 Python 页面绘制 PNG 和输出?谢谢!

【问题讨论】:

  • 您可能已经知道这一点,但如果您想要一个交互式图表而不是静态图像,您可以使用 mpld3 (mpld3.github.io)。

标签: python matplotlib


【解决方案1】:

首先,您需要一个页面来从生成图像的网络服务器控制器加载 url:

<img src="/matplot/makegraph?arg1=foo" />

然后,将 matplotlib 代码嵌入到 makegraph 控制器中。您只需要在内存缓冲区中捕获画布呈现的 PNG,然后创建 HTTP 响应并将字节写回浏览器:

import cStringIO
from matplotlib.figure import Figure                      
from matplotlib.backends.backend_agg import FigureCanvasAgg

fig = Figure(figsize=[4,4])                               
ax = fig.add_axes([.1,.1,.8,.8])                          
ax.scatter([1,2], [3,4])                                  
canvas = FigureCanvasAgg(fig)

# write image data to a string buffer and get the PNG image bytes
buf = cStringIO.StringIO()
canvas.print_png(buf)
data = buf.getvalue()

# pseudo-code for generating the http response from your
# webserver, and writing the bytes back to the browser.
# replace this with corresponding code for your web framework
headers = {
    'Content-Type': 'image/png',
    'Content-Length': len(data)
    }
response.write(200, 'OK', headers, data)

注意:如果它们经常使用相同的参数生成,您可能需要为它们添加缓存,例如从 args 构造一个 key 并将图像数据写入 memcache,然后在重新生成图形之前检查 memcache。

【讨论】:

  • 看来您也可以执行 plt.savefig(buf,format="png",facecolor="white") 或 fig.savefig()。所以你不必处理画布对象。
【解决方案2】:

只是为了更新python3

StringIO 和 cStringIO 模块消失了。相反,导入 io 模块并使用 io.StringIO https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio

所以现在应该是这样的:

import io
from matplotlib.figure import Figure     
from matplotlib import pyplot as plt                 

fig = Figure(figsize=[4,4])                               
ax = fig.add_axes([.1,.1,.8,.8])                          
ax.scatter([1,2], [3,4])                                  

buf = io.BytesIO()
fig.savefig(buf, format='png')
plt.close(fig)
data=buf.getvalue()

# In my case I would have used Django for the webpage
response = HttpResponse(data, content_type='image/png')
return response

【讨论】:

    猜你喜欢
    • 2014-11-02
    • 2020-02-28
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多