Hi Massimo,

thanks for you help!

i'm going ahead with little steps,  i stored your code in a web2py controller :

mpl.py espone index, plot_interference

i tried it without modification, or just changing the return function to :

        return dict(image=plot(data={'interferemce':[(x,x**2) for x in 
range(100)]}))

in a web2py view i have :

###
{{extend 'layout.html'}}
<h1>Image generated with matplotlib</h1>

<img src="{{=d}}" alt="Red dot" />
###

the rendered page : 
http://127.0.0.1:8000/welcome/mpl/plot_interference

looks like :
http://www.geofemengineering.it//img.png

i can see it is type() string, if i save it and add the .png extension i can 
display the image
that' a big step ahead if compared with my old 'static' plot function .. 
my problem (thanks for your patience) is that i'm still tying to understand
how to render that (string-image) in the web, and add a form to 'modify it' 
(change input parameters) ?

thanks!

Massimo.

Il giorno May 13, 2012, alle ore 9:56 PM, Massimo Di Pierro ha scritto:

> # useful module
> 
> import os, tempfile, random, cStringIO
> 
> 
> 
> # setup a temporary working forlder
> 
> os.environ['MPLCONfigureDIR'] = tempfile.mkdtemp()
> 
> 
> 
> # main matplotlib modules
> 
> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
> 
> from matplotlib.figure import Figure
> 
> 
> 
> # optional for scatter plots
> 
> from matplotlib.patches import Ellipse
> 
> 
> def plot(title='title',xlab='x',ylab='y',
> 
>          data={'xxx':[(0,0),(1,1),(1,2),(3,3)],
> 
>                'yyy':[(0,0,.2),(2,1,0.2),(2,2,0.2),(3,3,0.2)]}):
> 
> 
> 
>     figure=Figure(frameon=False)
> 
>     axes=figure.add_subplot(111)
> 
>     if title: axes.set_title(title)
> 
>     if xlab: axes.set_xlabel(xlab)
> 
>     if ylab: axes.set_ylabel(ylab)
> 
>     keys=sorted(data)                      # sort data series by name
> 
>     for key in keys:                       # for each data series
> 
>         stream = data[key]
> 
>         (x,y)=([],[])                      # make empty list x and empty list 
> y
> 
>         yerr = []                          # ... and empty list yerr 
> (optional)
> 
>         for point in stream:               # for each point in series
> 
>             x.append(point[0])             # append X coordinate to x
> 
>             y.append(point[1])             # append Y coordinate to y
> 
>             if len(point)==3:              # if dY, append dY to yerr
> 
>                 yerr.append(point[2])
> 
>         ell=axes.plot(x, y, linewidth="2") # plot y vs x 
> 
>         if len(yerr)==len(x):              # if error bars, display them
> 
>             axes.errorbar(x, y, yerr=yerr, fmt='o', linewidth="1")
> 
> 
> 
>     canvas=FigureCanvas(figure)
> 
>     stream=cStringIO.StringIO()
> 
>     canvas.print_png(stream)
> 
>     return stream.getvalue()
> 
> 
> 
> 
> def plot_interference():
> 
>     return plot(data={'interferemce':[(x,x**2) for x in range(100)]})
> 
> 
> 
> 
> 
> 
> On Sunday, 13 May 2012 13:02:37 UTC-5, epifanio wrote:
> 
> i'm looking for a solution, to start to write a web-app to generate graph 
> using matplotlib 
> the graph needs to be generated using some inputs parameters coming from the 
> page itself.
> 
> right now i'm rewriting the app from scratch ..  but i'm stuck on how to 
> integrate a query button to the python code .. 
> 
> essentially what i need to start is :
> 
> a page with a line-edit input box + Jquery widget (a simple button, will be 
> enough to learn more)
> 
> then connect the button to execute a generic python code that will use as 
> input the text in the line-edit 
> .. the generic python code will process the text received as input and return 
> the results on the same page where the line-edit and the button are.
> 
> i hope my description gives you an idea of what i was looking for
> 
> Many thanks for any help!
> 
> 
> Massimo.
> 
> 
> Il giorno May 11, 2012, alle ore 10:49 AM, Massimo Di Stefano ha scritto:
> 
>> 
>> Hi All,
>> 
>> i'm tring to learn web2py, thanks for the wonderful book and for the really 
>> nice tutorial!
>> i'm a bit 'stuck' on how to perform a simple task (i guess it is simple) 
>> because of my ignorance.
>> 
>> .. i'm bring to update dynamic a graph-chart (generated with matplotlib) 
>> using a form to pass the input the draw-function.
>> 
>> 
>> what i have is a controller :
>> 
>> # template_example.py  that 'espone' a function 'variables' , it will 
>> display an image generated by matplotlib using the 'stem_plot' function (in 
>> the same .py file)
>> 
>> 
>> # import a lib that generate the data from the url gived as input
>> from ecoopclimate import Climate
>> #import some matplotlib methodsm numpy ... 
>> from pylab import stem, setp, grid, savefig, show, gca, subplot, 
>> subplots_adjust
>> import matplotlib as mpl
>> import matplotlib.pyplot as plt
>> import datetime as dt
>> import numpy as np
>> # plot function
>> def stem_plot(data, name):
>>     data[np.isnan(data)]=0
>>     fig = plt.figure()
>>     ax = fig.add_subplot(211)
>>     mindate = int(data[0][0])
>>     maxdate = int(data[0][-1])
>>     date2_1 = dt.datetime(mindate, 1, 1)
>>     date2_2 = dt.datetime(maxdate, 1, 1)
>>     delta2 = dt.timedelta(days=365)
>>     dates2 = mpl.dates.drange(date2_1, date2_2, delta2)
>> 
>>     dateFmt = mpl.dates.DateFormatter('%Y')
>>     ax.xaxis.set_major_formatter(dateFmt)
>>     fig.autofmt_xdate(bottom=0.1) 
>>     x_p = dates2[np.where(data[1]>=0)[0]]
>>     y_p = data[1][np.where(data[1]>=0)[0]]
>>     x_n = dates2[np.where(data[1]<0)[0]]
>>     y_n = data[1][np.where(data[1]<0)[0]]
>> 
>>     markerline, stemlines, baseline = stem(x_p, y_p, 'r-')
>>     setp(markerline, 'markerfacecolor', 'b')
>>     setp(baseline, 'color', 'r', 'linewidth', 2)
>>     setp(stemlines, 'linewidth', 1)
>>     markerline, stemlines, baseline = stem(x_n, y_n, 'b-')
>>     setp(markerline, 'markerfacecolor', 'b')
>>     setp(baseline, 'color', 'r', 'linewidth', 2)
>>     setp(stemlines, 'linewidth', 1)
>>     grid()
>>     setp(gca(), 'xlabel', 'Year', 'ylabel', name)
>>     fig = '/Users/epifanio/web2py/applications/welcome/static/'+name+'.png'
>>     dateFmt = mpl.dates.DateFormatter('%Y')
>>     savefig(fig)
>>     return fig
>>     #show()
>> 
>> # function connected to the view : variables.html
>> def variables():
>>     nao_url = 
>> 'https://climatedataguide.ucar.edu/sites/default/files/cas_data_files/asphilli/nao_station_djfm.txt'
>>     clm = Climate()
>>     NAO = clm.nao(nao_url, 'nao.txt')
>>     image = stem_plot(NAO['nao'], 'nao')
>>     return dict(d=URL('static', 'nao.png'))
>> 
>> 
>> the view template_example/variables.html is : 
>> 
>> {{extend 'layout.html'}}
>> <h1>Image generated with matplotlib</h1>
>> 
>> <img src="{{=d}}" alt="Red dot" />
>> 
>> 
>> As you can see from the code in stem_plot it takes as input :  'data' and 
>> 'name'
>> i'm hardcoding the var inside the function 'variables' 
>> 
>> i need to modify that code adding a 'form' in the view that will take 2 
>> string as input
>> 
>> nao_url = 
>> 'https://climatedataguide.ucar.edu/sites/default/files/cas_data_files/asphilli/nao_station_djfm.txt'
>> image_name = 'imagename'
>> 
>> and pass this  input to the main function that generate the graph.
>> Have you any hints on how to do that ?
>> i'd like to have the form in the same page where the image is displayed
>> so that i can update the image every time i'll resubmit the form.
>> i'm a beginner, an example that does something like that will be really 
>> helpful :)
>> Many many Thanks for your help! 
>> Massimo.
>> 
>> 
>> 
>> 
>>  
> 

Reply via email to