|
From: Michael H. <mh...@al...> - 2011-02-22 09:16:13
|
On 02/21/2011 09:51 PM, John E Field wrote:
> I installed Gnuplot.py and I like it a lot. How about a really quick and
> easy routine to just plot a function or several functions. It seems like
> I am plotting things so much that I shouldn't have to write several
> lines of code to make it happen. Perhaps it is already in there and I
> just don't know about it. Something sort of like this :
I'm not such a fan of magical functions that try to guess what you mean.
The problem is that everybody has a different opinion about what magic
they prefer. I prefer flexible but straightforward functions that can
be *used* to make magical functions. So I wouldn't advocate putting a
function like this in Gnuplot.py, though it is a fine example.
> gplot(x,y) <- plots y vs x
> gplot(x,y,with_='lines',title='my title') <- adds title and plots with lines
> gplot(x,y,z) <- plots y and z versus x
> gplot([1,2],sin) <- plots sin(x) from 1.0 to 2.0
>
> and, the code might look something like this :
>
> def gplot(*xy,**args) :
> """ routine for plotting a function using gnuplot directly from python
> usage: pass arguments in args. for with lines, do with_='lines'
> title = 'my title'
> xlabel= 'my xlabel',
> etc.
> if the persist option is false, then the plot will only last
> until the returned object is destroyed
> otherwise, the plot is forever.
> """
> try :
> if args.has_key('persist') :
> g = Gnuplot.Gnuplot(persist=args['persist']);
> del args['persist'];
> else : g = Gnuplot.Gnuplot(persist=True);
> except :
> from Gnuplot import Gnuplot,Data
> if args.has_key('persist') :
> g = Gnuplot(persist=args['persist']);
> del args['persist'];
> else : g = Gnuplot(persist=True);
> x = xy[0];
> if len(x) == 2 : # fill up the range
> x = [x[0]+(x[1]-x[0])*0.005*i for i in range(201)];
> d = []; # make an argument list for each plot function
> for yi in xy[1:] :
> if not (yi.__class__ is list or yi.__class__ is tuple) : yi =
> map(yi,x);
> if args.has_key('with_') :
> di = Data(x,yi,with_=args['with_']);
> else : di = Data(x,yi);
> d.append(di);
> if args.has_key('with_') : del args['with_'];
> return g.plot(*d,**args);
BTW, there are some things in your function that can be simplified
(untested code):
def gplot(*xy,**args):
"""..."""
try:
Gnuplot, Data
except NameError:
from Gnuplot import Gnuplot, Data
g = Gnuplot(persist=args.pop('persist', True));
x = xy[0]
if len(x) == 2:
# fill up the range
x = [x[0]+(x[1]-x[0])*0.005*i for i in range(201)]
d = [] # make an argument list for each plot function
data_opts = {}
if 'with_' in args:
data_opts['with_'] = args.pop('with_')
for yi in xy[1:]:
if not isinstance(yi, (list, tuple)):
yi = map(yi,x)
d.append(Data(x, yi, **data_args))
return g.plot(*d, **args)
Michael
--
Michael Haggerty
mh...@al...
http://softwareswirl.blogspot.com/
|