Any way to speed up the load time for matplotlib for a web server (django)app?
I am drawing some colorful scatter plots using matplotlib in my django app for some small data sets, but the import statements add about 1-2 seconds to the run time compared to my previous version which used a javascript graphing utility - so now it takes almost 3 seconds instead of under a 1/2 second to load the page. It bugs me, even though most people at my office won't care.
Here's the basic code:
from matplotlib.backends.backend_agg import FigureCanvasAgg as Fig开发者_运维问答ureCanvas
from matplotlib.figure import Figure
fig = Figure(figsize=[7, 7] )
canvas = FigureCanvas(fig)
ax = fig.add_axes( [1, 1, 5, 5] )
ax.scatter( x, y, c=colors, s=15, linewidth=1.5)
ax.set_xticklabels(labels, rotation=-40, horizontalalignment='left')
fig.savefig(file)
Is there a more light-weight method to load the Figure - or perhaps a different backend is faster?
I switched from the javascript utility because my co-workers needed to be able to copy and paste the image from the website. I like the idea of using matplotlib because now I can make some fancier graphs, but I am open to a different lightweight tool if that would have better performance.
Another idea would be to make some sort of server app which is always running and listens to a port for the query and then sends back the image. Then it would NOT have to load the whole matplotlib library for each query. But, that sounds like a lot of work.
You should render the image in a separate view. This lets your browser start rendering the page while the image (or images) are still being generated.
def view(request):
...
response=django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
(Code from http://www.scipy.org/Cookbook/Matplotlib/Django)
Furthermore, Django's processes shouldn't die after each page request. Try configuring Apache/Nginx to keep multiple processes alive for future page requests. Each process will have to execute the import
statements the first time it renders your image view. After that, you should have speedups.
精彩评论