在网络上绘制matplotlib [英] Plot matplotlib on the Web

查看:83
本文介绍了在网络上绘制matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code will of course create a PNG named test and save it on the server:

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和输出?谢谢!

Then to view the image in the browser, we have to go to example.com/test.png. This means we have to call the page with the Python code first to create the test.png file, then go to the PNG file. Is there a way to draw the PNG and output from the Python page that creates the image? Thanks!

推荐答案

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

First you need a page to load a url from the webserver controller which generates the image:

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

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

Then, embed the matplotlib code into the makegraph controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write the bytes back to the browser:

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构造一个键,然后将图像数据写入memcache,然后在重新生成图形之前检查memcache.

Note: you may want to add caching for these if they're frequently generated with the same arguments, e.g. construct a key from the args and write the image data to memcache, then check memcache before regenerating the graph.

这篇关于在网络上绘制matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆