问题
I am using Plone 4.3 with matplotlib. I have the plot window but I want to render the plot window in a page template. Some folks suggested I use HTML5 canvas
to render the plot window in a template page. But I am unable to grasp that concept. So anyone can help me?
回答1:
Create a browser view, set the header type, and return the image data e.g.
from zope.publisher.browser import BrowserPage
class PloneMatPlotLib(BrowserPage):
"""
"""
def __call__(self):
import cStringIO
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
x, y = 4, 4
fig = Figure(figsize=[x, y])
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()
# write image bytes back to the browser
self.request.response.setHeader("Content-type", "image/png")
return data
You can then call this view TTW (through the web) to get the image e.g. http://localhost:8080/Plone/@@plone_matplotlib
. Or in a page template e.g.:
<div metal:use-macro="here/main_template/macros/master">
<div metal:fill-slot="main">
<img tal:attributes="src python:context.absolute_url() + '/@@plone_matplotlib'">
</div>
</div>
More here:
- https://github.com/aclark4life/plone_matplotlib
来源:https://stackoverflow.com/questions/23779160/how-to-use-matplotlib-in-plone