Plotting graph on pys60
I try to replicate some easy examples in
matplotlib tutorial.
First, we need a float range function.
1 2 from __future__ import generators 3 4 def arange(start, stop=None, step=None): 5 if stop is None: 6 stop = float(start) 7 start = 0.0 8 if step is None: 9 step = 1.0 10 cur = float(start) 11 while cur < stop: 12 yield cur 13 cur += step
Then, a function to draw the axes and ticks.
In the future, this should be called automatically from plot().
1 2 from appuifw import * 3 app.body = canvas = Canvas() 4 width, height = canvas.size 5 6 def axes(xyrange, position=[18, height-11, width-10, 10], formatter=lambda x:x): 7 global left, bottom, right, top, min_x, min_y, scale_x, scale_y 8 left, bottom, right, top = position 9 min_x, max_x, step_x, min_y, max_y, step_y = xyrange 10 scale_x = float(right-left)/(max_x-min_x) 11 scale_y = float(bottom-top)/(max_y-min_y) 12 canvas.clear() 13 canvas.rectangle([(left,top), (right+1, bottom+1)], 0) 14 for x in arange(min_x, max_x, step_x): 15 canvas.text((14+scale_x*(x-min_x), height-1), unicode(formatter(x))) 16 canvas.point((left+scale_x*(x-min_x), bottom-1), 0) 17 canvas.point((left+scale_x*(x-min_x), top+1), 0) 18 for y in arange(min_y, max_y, step_y): 19 canvas.text((2, bottom+2-scale_y*(y-min_y)), unicode(formatter(y))) 20 canvas.point((left+1, bottom-scale_y*(y-min_y)), 0) 21 canvas.point((right-1, bottom-scale_y*(y-min_y)), 0)
And lastly, the plot function. Now it has only a few features.
More will be added depending on what is needed.
1 2 def plot(xs, ys=None): 3 if ys==None: 4 ys = xs 5 xs = range(len(ys)) 6 last = left+(xs[0]-min_x)*scale_x, bottom-(ys[0]-min_y)*scale_y 7 for i in range(1, len(ys)): 8 p = left+(xs[i]-min_x)*scale_x, bottom-(ys[i]-min_y)*scale_y 9 canvas.line([last, p], 0x00000ff) 10 last = p 11 canvas.point(last, 0x0000ff)
When we want to plot a graph, we called both axes() and plot()
1 2 # a straight line 3 >>> axes([0,3.1,.5, 1,4.1,.5]) 4 >>> plot([1,2,3,4]) 5 6 # a parabola y = x^2 7 >>> axes([1,4.1,1, 0,16.1,2], formatter=int) 8 >>> plot([1,2,3,4], [1,4,9,16])
See the sreenshot of the first.