Debian Codegraph @

examples/accelerometer/using_graph/libs/garden/garden.graph/__init__.py

raw symbols SCIP
1 '''
2 Graph
3 ======
4
5 The :class:`Graph` widget is a widget for displaying plots. It supports
6 drawing multiple plot with different colors on the Graph. It also supports
7 a title, ticks, labeled ticks, grids and a log or linear representation on
8 both the x and y axis, independently.
9
10 To display a plot. First create a graph which will function as a "canvas" for
11 the plots. Then create plot objects e.g. MeshLinePlot and add them to the
12 graph.
13
14 To create a graph with x-axis between 0-100, y-axis between -1 to 1, x and y
15 labels of and X and Y, respectively, x major and minor ticks every 25, 5 units,
16 respectively, y major ticks every 1 units, full x and y grids and with
17 a red line plot containing a sin wave on this range::
18
19 from kivy.garden.graph import Graph, MeshLinePlot
20 graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
21 x_ticks_major=25, y_ticks_major=1,
22 y_grid_label=True, x_grid_label=True, padding=5,
23 x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
24 plot = MeshLinePlot(color=[1, 0, 0, 1])
25 plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
26 graph.add_plot(plot)
27
28 The MeshLinePlot plot is a particular plot which draws a set of points using
29 a mesh object. The points are given as a list of tuples, with each tuple
30 being a (x, y) coordinate in the graph's units.
31
32 You can create different types of plots other than MeshLinePlot by inheriting
33 from the Plot class and implementing the required functions. The Graph object
34 provides a "canvas" to which a Plot's instructions are added. The plot object
35 is responsible for updating these instructions to show within the bounding
36 box of the graph the proper plot. The Graph notifies the Plot when it needs
37 to be redrawn due to changes. See the MeshLinePlot class for how it is done.
38
39 .. note::
40
41 The graph uses a stencil view to clip the plots to the graph display area.
42 As with the stencil graphics instructions, you cannot stack more than 8
43 stencil-aware widgets.
44
45 '''
46
47 __all__ = ('Graph', 'Plot', 'MeshLinePlot', 'MeshStemPlot')
48
49 from math import radians
50 from kivy.uix.widget import Widget
51 from kivy.uix.label import Label
52 from kivy.uix.stencilview import StencilView
53 from kivy.properties import NumericProperty, BooleanProperty,\
54 BoundedNumericProperty, StringProperty, ListProperty, ObjectProperty,\
55 DictProperty, AliasProperty
56 from kivy.clock import Clock
57 from kivy.graphics import Mesh, Color
58 from kivy.graphics.transformation import Matrix
59 from kivy.event import EventDispatcher
60 from kivy.lang import Builder
61 from kivy import metrics
62 from math import log10, floor, ceil
63 from decimal import Decimal
64
65 Builder.load_string('''
66 #:kivy 1.1.0
67
68 <RotateLabel>:
69 canvas.before:
70 PushMatrix
71 MatrixInstruction:
72 matrix: self.transform
73 canvas.after:
74 PopMatrix
75
76 ''')
77
78
79 class RotateLabel(Label):
80
81 transform = ObjectProperty(Matrix())
82
83
84 class Graph(Widget):
85 '''Graph class, see module documentation for more information.
86 '''
87
88 # triggers a full reload of graphics
89 _trigger = ObjectProperty(None)
90 # triggers only a repositioning of objects due to size/pos updates
91 _trigger_size = ObjectProperty(None)
92 # holds widget with the x-axis label
93 _xlabel = ObjectProperty(None)
94 # holds widget with the y-axis label
95 _ylabel = ObjectProperty(None)
96 # holds all the x-axis tick mark labels
97 _x_grid_label = ListProperty([])
98 # holds all the y-axis tick mark labels
99 _y_grid_label = ListProperty([])
100 # holds the stencil view that clipse the plots to graph area
101 _plot_area = ObjectProperty(None)
102 # the mesh drawing all the ticks/grids
103 _mesh = ObjectProperty(None)
104 # the mesh which draws the surrounding rectangle
105 _mesh_rect = ObjectProperty(None)
106 # a list of locations of major and minor ticks. The values are not
107 # but is in the axis min - max range
108 _ticks_majorx = ListProperty([])
109 _ticks_minorx = ListProperty([])
110 _ticks_majory = ListProperty([])
111 _ticks_minory = ListProperty([])
112
113 def __init__(self, **kwargs):
114 super().__init__(**kwargs)
115
116 self._mesh = Mesh(mode='lines')
117 self._mesh_rect = Mesh(mode='line_strip')
118 val = 0.25
119 self.canvas.add(Color(1 * val, 1 * val, 1 * val))
120 self.canvas.add(self._mesh)
121 self.canvas.add(Color(1, 1, 1))
122 self.canvas.add(self._mesh_rect)
123 mesh = self._mesh_rect
124 mesh.vertices = [0] * (5 * 4)
125 mesh.indices = [k for k in range(5)]
126
127 self._plot_area = StencilView()
128 self.add_widget(self._plot_area)
129
130 self._trigger = Clock.create_trigger(self._redraw_all)
131 self._trigger_size = Clock.create_trigger(self._redraw_size)
132
133 self.bind(center=self._trigger_size, padding=self._trigger_size,
134 font_size=self._trigger_size, plots=self._trigger_size,
135 x_grid=self._trigger_size, y_grid=self._trigger_size,
136 draw_border=self._trigger_size)
137 self.bind(xmin=self._trigger, xmax=self._trigger,
138 xlog=self._trigger, x_ticks_major=self._trigger,
139 x_ticks_minor=self._trigger,
140 xlabel=self._trigger, x_grid_label=self._trigger,
141 ymin=self._trigger, ymax=self._trigger,
142 ylog=self._trigger, y_ticks_major=self._trigger,
143 y_ticks_minor=self._trigger,
144 ylabel=self._trigger, y_grid_label=self._trigger)
145 self._trigger()
146
147 def _get_ticks(self, major, minor, log, s_min, s_max):
148 if major and s_max > s_min:
149 if log:
150 s_min = log10(s_min)
151 s_max = log10(s_max)
152 # count the decades in min - max. This is in actual decades,
153 # not logs.
154 n_decades = floor(s_max - s_min)
155 # for the fractional part of the last decade, we need to
156 # convert the log value, x, to 10**x but need to handle
157 # differently if the last incomplete decade has a decade
158 # boundary in it
159 if floor(s_min + n_decades) != floor(s_max):
160 n_decades += 1 - (10 ** (s_min + n_decades + 1) - 10
161 ** s_max) / 10 ** floor(s_max + 1)
162 else:
163 n_decades += ((10 ** s_max - 10 ** (s_min + n_decades))
164 / 10 ** floor(s_max + 1))
165 # this might be larger than what is needed, but we delete
166 # excess later
167 n_ticks_major = n_decades / float(major)
168 n_ticks = int(floor(n_ticks_major * (minor if minor
169 >= 1. else 1.0))) + 2
170 # in decade multiples, e.g. 0.1 of the decade, the distance
171 # between ticks
172 decade_dist = major / float(minor if minor else 1.0)
173
174 points_minor = [0] * n_ticks
175 points_major = [0] * n_ticks
176 k = 0 # position in points major
177 k2 = 0 # position in points minor
178 # because each decade is missing 0.1 of the decade, if a tick
179 # falls in < min_pos skip it
180 min_pos = 0.1 - 0.00001 * decade_dist
181 s_min_low = floor(s_min)
182 # first real tick location. value is in fractions of decades
183 # from the start we have to use decimals here, otherwise
184 # floating point inaccuracies results in bad values
185 start_dec = ceil((10 ** Decimal(s_min - s_min_low - 1))
186 / Decimal(decade_dist)) * decade_dist
187 count_min = (0 if not minor else
188 floor(start_dec / decade_dist) % minor)
189 start_dec += s_min_low
190 count = 0 # number of ticks we currently have passed start
191 while True:
192 # this is the current position in decade that we are.
193 # e.g. -0.9 means that we're at 0.1 of the 10**ceil(-0.9)
194 # decade
195 pos_dec = start_dec + decade_dist * count
196 pos_dec_low = floor(pos_dec)
197 diff = pos_dec - pos_dec_low
198 zero = abs(diff) < 0.001 * decade_dist
199 if zero:
200 # the same value as pos_dec but in log scale
201 pos_log = pos_dec_low
202 else:
203 pos_log = log10((pos_dec - pos_dec_low
204 ) * 10 ** ceil(pos_dec))
205 if pos_log > s_max:
206 break
207 count += 1
208 if zero or diff >= min_pos:
209 if minor and not count_min % minor:
210 points_major[k] = pos_log
211 k += 1
212 else:
213 points_minor[k2] = pos_log
214 k2 += 1
215 count_min += 1
216 # n_ticks = len(points)
217 else:
218 # distance between each tick
219 tick_dist = major / float(minor if minor else 1.0)
220 n_ticks = int(floor((s_max - s_min) / tick_dist) + 1)
221 points_major = [0] * int(
222 floor((s_max - s_min) / float(major)) + 1
223 )
224 points_minor = [0] * (n_ticks - len(points_major) + 1)
225 k = 0 # position in points major
226 k2 = 0 # position in points minor
227 for m in range(0, n_ticks):
228 if minor and m % minor:
229 points_minor[k2] = m * tick_dist + s_min
230 k2 += 1
231 else:
232 points_major[k] = m * tick_dist + s_min
233 k += 1
234 del points_major[k:]
235 del points_minor[k2:]
236 else:
237 points_major = []
238 points_minor = []
239 return points_major, points_minor
240
241 def _update_labels(self):
242 xlabel = self._xlabel
243 ylabel = self._ylabel
244 x = self.x
245 y = self.y
246 width = self.width
247 height = self.height
248 padding = self.padding
249 x_next = padding + x
250 y_next = padding + y
251 xextent = x + width
252 yextent = y + height
253 ymin = self.ymin
254 ymax = self.ymax
255 xmin = self.xmin
256 precision = self.precision
257 x_overlap = False
258 y_overlap = False
259 # set up x and y axis labels
260 if xlabel:
261 xlabel.text = self.xlabel
262 xlabel.texture_update()
263 xlabel.size = xlabel.texture_size
264 xlabel.pos = (x + width / 2. - xlabel.width / 2., padding + y)
265 y_next += padding + xlabel.height
266 if ylabel:
267 ylabel.text = self.ylabel
268 ylabel.texture_update()
269 ylabel.size = ylabel.texture_size
270 ylabel.x = padding + x - (ylabel.width / 2. - ylabel.height / 2.)
271 x_next += padding + ylabel.height
272 xpoints = self._ticks_majorx
273 xlabels = self._x_grid_label
274 xlabel_grid = self.x_grid_label
275 ylabel_grid = self.y_grid_label
276 ypoints = self._ticks_majory
277 ylabels = self._y_grid_label
278 # now x and y tick mark labels
279 if len(ylabels) and ylabel_grid:
280 # horizontal size of the largest tick label, to have enough room
281 ylabels[0].text = precision % ypoints[0]
282 ylabels[0].texture_update()
283 y1 = ylabels[0].texture_size
284 y_start = y_next + (
285 padding + y1[1]
286 if len(xlabels) and xlabel_grid else 0
287 ) + (padding + y1[1] if not y_next else 0)
288 yextent = y + height - padding - y1[1] / 2.
289 if self.ylog:
290 ymax = log10(ymax)
291 ymin = log10(ymin)
292 ratio = (yextent - y_start) / float(ymax - ymin)
293 y_start -= y1[1] / 2.
294 func = (lambda x: 10 ** x) if self.ylog else lambda x: x
295 y1 = y1[0]
296 for k in range(len(ylabels)):
297 ylabels[k].text = precision % func(ypoints[k])
298 ylabels[k].texture_update()
299 ylabels[k].size = ylabels[k].texture_size
300 y1 = max(y1, ylabels[k].texture_size[0])
301 ylabels[k].pos = (x_next, y_start + (ypoints[k] - ymin)
302 * ratio)
303 if len(ylabels) > 1 and ylabels[0].top > ylabels[1].y:
304 y_overlap = True
305 else:
306 x_next += y1 + padding
307 if len(xlabels) and xlabel_grid:
308 func = log10 if self.xlog else lambda x: x
309 # find the distance from the end that'll fit the last tick label
310 xlabels[0].text = precision % func(xpoints[-1])
311 xlabels[0].texture_update()
312 xextent = x + width - xlabels[0].texture_size[0] / 2. - padding
313 # find the distance from the start that'll fit the first tick label
314 if not x_next:
315 xlabels[0].text = precision % func(xpoints[0])
316 xlabels[0].texture_update()
317 x_next = padding + xlabels[0].texture_size[0] / 2.
318 xmin = func(xmin)
319 ratio = (xextent - x_next) / float(func(self.xmax) - xmin)
320 func = (lambda x: 10 ** x) if self.xlog else lambda x: x
321 right = -1
322 for k in range(len(xlabels)):
323 xlabels[k].text = precision % func(xpoints[k])
324 # update the size so we can center the labels on ticks
325 xlabels[k].texture_update()
326 xlabels[k].size = xlabels[k].texture_size
327 xlabels[k].pos = (x_next + (xpoints[k] - xmin) * ratio
328 - xlabels[k].texture_size[0] / 2., y_next)
329 if xlabels[k].x < right:
330 x_overlap = True
331 break
332 right = xlabels[k].right
333 if not x_overlap:
334 y_next += padding + xlabels[0].texture_size[1]
335 # now re-center the x and y axis labels
336 if xlabel:
337 xlabel.x = x_next + (xextent - x_next) / 2. - xlabel.width / 2.
338 if ylabel:
339 ylabel.y = y_next + (yextent - y_next) / 2. - ylabel.height / 2.
340 t = Matrix().translate(ylabel.center[0], ylabel.center[1], 0)
341 t = t.multiply(Matrix().rotate(-radians(270), 0, 0, 1))
342 ylabel.transform = t.multiply(Matrix().translate(-ylabel.center[0],
343 -ylabel.center[1],
344 0))
345 if x_overlap:
346 for k in range(len(xlabels)):
347 xlabels[k].text = ''
348 if y_overlap:
349 for k in range(len(ylabels)):
350 ylabels[k].text = ''
351 return x_next, y_next, xextent, yextent
352
353 def _update_ticks(self, size):
354 # re-compute the positions of the bounding rectangle
355 mesh = self._mesh_rect
356 vert = mesh.vertices
357 if self.draw_border:
358 vert[0] = size[0]
359 vert[1] = size[1]
360 vert[4] = size[2]
361 vert[5] = size[1]
362 vert[8] = size[2]
363 vert[9] = size[3]
364 vert[12] = size[0]
365 vert[13] = size[3]
366 vert[16] = size[0]
367 vert[17] = size[1]
368 else:
369 vert[0:18] = [0 for k in range(18)]
370 mesh.vertices = vert
371 # re-compute the positions of the x/y axis ticks
372 mesh = self._mesh
373 vert = mesh.vertices
374 start = 0
375 xpoints = self._ticks_majorx
376 ypoints = self._ticks_majory
377 ylog = self.ylog
378 xlog = self.xlog
379 xmin = self.xmin
380 xmax = self.xmax
381 if xlog:
382 xmin = log10(xmin)
383 xmax = log10(xmax)
384 ymin = self.ymin
385 ymax = self.ymax
386 if ylog:
387 xmin = log10(ymin)
388 ymax = log10(ymax)
389 if len(xpoints):
390 top = size[3] if self.x_grid else metrics.dp(12) + size[1]
391 ratio = (size[2] - size[0]) / float(xmax - xmin)
392 for k in range(start, len(xpoints) + start):
393 vert[k * 8] = size[0] + (xpoints[k - start] - xmin) * ratio
394 vert[k * 8 + 1] = size[1]
395 vert[k * 8 + 4] = vert[k * 8]
396 vert[k * 8 + 5] = top
397 start += len(xpoints)
398 if len(ypoints):
399 top = size[2] if self.y_grid else metrics.dp(12) + size[0]
400 ratio = (size[3] - size[1]) / float(ymax - ymin)
401 for k in range(start, len(ypoints) + start):
402 vert[k * 8 + 1] = size[1] + (ypoints[k - start] - ymin) * ratio
403 vert[k * 8 + 5] = vert[k * 8 + 1]
404 vert[k * 8] = size[0]
405 vert[k * 8 + 4] = top
406 mesh.vertices = vert
407
408 def _update_plots(self, size):
409 ylog = self.ylog
410 xlog = self.xlog
411 xmin = self.xmin
412 xmax = self.xmax
413 ymin = self.ymin
414 ymax = self.ymax
415 for plot in self.plots:
416 plot._update(xlog, xmin, xmax, ylog, ymin, ymax, size)
417
418 def _redraw_all(self, *args):
419 # add/remove all the required labels
420 font_size = self.font_size
421 if self.xlabel:
422 if not self._xlabel:
423 xlabel = Label(font_size=font_size)
424 self.add_widget(xlabel)
425 self._xlabel = xlabel
426 else:
427 xlabel = self._xlabel
428 if xlabel:
429 self.remove_widget(xlabel)
430 self._xlabel = None
431 grids = self._x_grid_label
432 xpoints_major, xpoints_minor = self._get_ticks(self.x_ticks_major,
433 self.x_ticks_minor,
434 self.xlog, self.xmin,
435 self.xmax)
436 self._ticks_majorx = xpoints_major
437 self._ticks_minorx = xpoints_minor
438 if not self.x_grid_label:
439 n_labels = 0
440 else:
441 n_labels = len(xpoints_major)
442 for k in range(n_labels, len(grids)):
443 self.remove_widget(grids[k])
444 del grids[n_labels:]
445 grid_len = len(grids)
446 grids.extend([None] * (n_labels - len(grids)))
447 for k in range(grid_len, n_labels):
448 grids[k] = Label(font_size=font_size)
449 self.add_widget(grids[k])
450
451 if self.ylabel:
452 if not self._ylabel:
453 ylabel = RotateLabel(font_size=font_size)
454 self.add_widget(ylabel)
455 self._ylabel = ylabel
456 else:
457 ylabel = self._ylabel
458 if ylabel:
459 self.remove_widget(ylabel)
460 self._ylabel = None
461 grids = self._y_grid_label
462 ypoints_major, ypoints_minor = self._get_ticks(self.y_ticks_major,
463 self.y_ticks_minor,
464 self.ylog, self.ymin,
465 self.ymax)
466 self._ticks_majory = ypoints_major
467 self._ticks_minory = ypoints_minor
468 if not self.y_grid_label:
469 n_labels = 0
470 else:
471 n_labels = len(ypoints_major)
472 for k in range(n_labels, len(grids)):
473 self.remove_widget(grids[k])
474 del grids[n_labels:]
475 grid_len = len(grids)
476 grids.extend([None] * (n_labels - len(grids)))
477 for k in range(grid_len, n_labels):
478 grids[k] = Label(font_size=font_size)
479 self.add_widget(grids[k])
480
481 mesh = self._mesh
482 n_points = (len(xpoints_major) + len(xpoints_minor)
483 + len(ypoints_major) + len(ypoints_minor))
484 mesh.vertices = [0] * (n_points * 8)
485 mesh.indices = [k for k in range(n_points * 2)]
486 self._redraw_size()
487
488 def _redraw_size(self, *args):
489 # size a 4-tuple describing the bounding box in which we can draw
490 # graphs, it's (x0, y0, x1, y1), which correspond with the bottom left
491 # and top right corner locations, respectively
492 size = self._update_labels()
493 self._plot_area.pos = (size[0], size[1])
494 self._plot_area.size = (size[2] - size[0], size[3] - size[1])
495 self._update_ticks(size)
496 self._update_plots(size)
497
498 def add_plot(self, plot):
499 '''Add a new plot to this graph.
500
501 :Parameters:
502 `plot`:
503 Plot to add to this graph.
504
505 >>> graph = Graph()
506 >>> plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1])
507 >>> plot.points = [(x / 10., sin(x / 50.)) for x in range(-0, 101)]
508 >>> graph.add_plot(plot)
509 '''
510 area = self._plot_area
511 for group in plot._get_drawings():
512 area.canvas.add(group)
513 self.plots = self.plots + [plot]
514
515 def remove_plot(self, plot):
516 '''Remove a plot from this graph.
517
518 :Parameters:
519 `plot`:
520 Plot to remove from this graph.
521
522 >>> graph = Graph()
523 >>> plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1])
524 >>> plot.points = [(x / 10., sin(x / 50.)) for x in range(-0, 101)]
525 >>> graph.add_plot(plot)
526 >>> graph.remove_plot(plot)
527 '''
528 self._plot_area.canvas.remove_group(plot._get_group())
529 self.plots.remove(plot)
530
531 xmin = NumericProperty(0.)
532 '''The x-axis minimum value.
533
534 If :data:`xlog` is True, xmin must be larger than zero.
535
536 :data:`xmin` is a :class:`~kivy.properties.NumericProperty`, defaults to 0.
537 '''
538
539 xmax = NumericProperty(100.)
540 '''The x-axis maximum value, larger than xmin.
541
542 :data:`xmax` is a :class:`~kivy.properties.NumericProperty`, defaults to 0.
543 '''
544
545 xlog = BooleanProperty(False)
546 '''Determines whether the x-axis should be displayed logarithmically (True)
547 or linearly (False).
548
549 :data:`xlog` is a :class:`~kivy.properties.BooleanProperty`, defaults
550 to False.
551 '''
552
553 x_ticks_major = BoundedNumericProperty(0, min=0)
554 '''Distance between major tick marks on the x-axis.
555
556 Determines the distance between the major tick marks. Major tick marks
557 start from min and re-occur at every ticks_major until :data:`xmax`.
558 If :data:`xmax` doesn't overlap with a integer multiple of ticks_major,
559 no tick will occur at :data:`xmax`. Zero indicates no tick marks.
560
561 If :data:`xlog` is true, then this indicates the distance between ticks
562 in multiples of current decade. E.g. if :data:`xmin` is 0.1 and
563 ticks_major is 0.1, it means there will be a tick at every 10th of the
564 decade, i.e. 0.1 ... 0.9, 1, 2... If it is 0.3, the ticks will occur at
565 0.1, 0.3, 0.6, 0.9, 2, 5, 8, 10. You'll notice that it went from 8 to 10
566 instead of to 20, that's so that we can say 0.5 and have ticks at every
567 half decade, e.g. 0.1, 0.5, 1, 5, 10, 50... Similarly, if ticks_major is
568 1.5, there will be ticks at 0.1, 5, 100, 5,000... Also notice, that there's
569 always a major tick at the start. Finally, if e.g. :data:`xmin` is 0.6
570 and this 0.5 there will be ticks at 0.6, 1, 5...
571
572 :data:`x_ticks_major` is a
573 :class:`~kivy.properties.BoundedNumericProperty`, defaults to 0.
574 '''
575
576 x_ticks_minor = BoundedNumericProperty(0, min=0)
577 '''The number of sub-intervals that divide x_ticks_major.
578
579 Determines the number of sub-intervals into which ticks_major is divided,
580 if non-zero. The actual number of minor ticks between the major ticks is
581 ticks_minor - 1. Only used if ticks_major is non-zero. If there's no major
582 tick at xmax then the number of minor ticks after the last major
583 tick will be however many ticks fit until xmax.
584
585 If self.xlog is true, then this indicates the number of intervals the
586 distance between major ticks is divided. The result is the number of
587 multiples of decades between ticks. I.e. if ticks_minor is 10, then if
588 ticks_major is 1, there will be ticks at 0.1, 0.2...0.9, 1, 2, 3... If
589 ticks_major is 0.3, ticks will occur at 0.1, 0.12, 0.15, 0.18... Finally,
590 as is common, if ticks major is 1, and ticks minor is 5, there will be
591 ticks at 0.1, 0.2, 0.4... 0.8, 1, 2...
592
593 :data:`x_ticks_minor` is a
594 :class:`~kivy.properties.BoundedNumericProperty`, defaults to 0.
595 '''
596
597 x_grid = BooleanProperty(False)
598 '''Determines whether the x-axis has tick marks or a full grid.
599
600 If :data:`x_ticks_major` is non-zero, then if x_grid is False tick marks
601 will be displayed at every major tick. If x_grid is True, instead of ticks,
602 a vertical line will be displayed at every major tick.
603
604 :data:`x_grid` is a :class:`~kivy.properties.BooleanProperty`, defaults
605 to False.
606 '''
607
608 x_grid_label = BooleanProperty(False)
609 '''Whether labels should be displayed beneath each major tick. If true,
610 each major tick will have a label containing the axis value.
611
612 :data:`x_grid_label` is a :class:`~kivy.properties.BooleanProperty`,
613 defaults to False.
614 '''
615
616 xlabel = StringProperty('')
617 '''The label for the x-axis. If not empty it is displayed in the center of
618 the axis.
619
620 :data:`xlabel` is a :class:`~kivy.properties.StringProperty`,
621 defaults to ''.
622 '''
623
624 ymin = NumericProperty(0.)
625 '''The y-axis minimum value.
626
627 If :data:`ylog` is True, ymin must be larger than zero.
628
629 :data:`ymin` is a :class:`~kivy.properties.NumericProperty`, defaults to 0.
630 '''
631
632 ymax = NumericProperty(100.)
633 '''The y-axis maximum value, larger than ymin.
634
635 :data:`ymax` is a :class:`~kivy.properties.NumericProperty`, defaults to 0.
636 '''
637
638 ylog = BooleanProperty(False)
639 '''Determines whether the y-axis should be displayed logarithmically (True)
640 or linearly (False).
641
642 :data:`ylog` is a :class:`~kivy.properties.BooleanProperty`, defaults
643 to False.
644 '''
645
646 y_ticks_major = BoundedNumericProperty(0, min=0)
647 '''Distance between major tick marks. See :data:`x_ticks_major`.
648
649 :data:`y_ticks_major` is a
650 :class:`~kivy.properties.BoundedNumericProperty`, defaults to 0.
651 '''
652
653 y_ticks_minor = BoundedNumericProperty(0, min=0)
654 '''The number of sub-intervals that divide ticks_major.
655 See :data:`x_ticks_minor`.
656
657 :data:`y_ticks_minor` is a
658 :class:`~kivy.properties.BoundedNumericProperty`, defaults to 0.
659 '''
660
661 y_grid = BooleanProperty(False)
662 '''Determines whether the y-axis has tick marks or a full grid. See
663 :data:`x_grid`.
664
665 :data:`y_grid` is a :class:`~kivy.properties.BooleanProperty`, defaults
666 to False.
667 '''
668
669 y_grid_label = BooleanProperty(False)
670 '''Whether labels should be displayed beneath each major tick. If true,
671 each major tick will have a label containing the axis value.
672
673 :data:`y_grid_label` is a :class:`~kivy.properties.BooleanProperty`,
674 defaults to False.
675 '''
676
677 ylabel = StringProperty('')
678 '''The label for the y-axis. If not empty it is displayed in the center of
679 the axis.
680
681 :data:`ylabel` is a :class:`~kivy.properties.StringProperty`,
682 defaults to ''.
683 '''
684
685 padding = NumericProperty('5dp')
686 '''Padding distances between the labels, titles and graph, as well between
687 the widget and the objects near the boundaries.
688
689 :data:`padding` is a :class:`~kivy.properties.NumericProperty`, defaults
690 to 5dp.
691 '''
692
693 font_size = NumericProperty('15sp')
694 '''Font size of the labels.
695
696 :data:`font_size` is a :class:`~kivy.properties.NumericProperty`, defaults
697 to 15sp.
698 '''
699
700 precision = StringProperty('%g')
701 '''Determines the numerical precision of the tick mark labels. This value
702 governs how the numbers are converted into string representation. Accepted
703 values are those listed in Python's manual in the
704 "String Formatting Operations" section.
705
706 :data:`precision` is a :class:`~kivy.properties.StringProperty`, defaults
707 to '%g'.
708 '''
709
710 draw_border = BooleanProperty(True)
711 '''Whether a border is drawn around the canvas of the graph where the
712 plots are displayed.
713
714 :data:`draw_border` is a :class:`~kivy.properties.BooleanProperty`,
715 defaults to True.
716 '''
717
718 plots = ListProperty([])
719 '''Holds a list of all the plots in the graph. To add and remove plots
720 from the graph use :data:`add_plot` and :data:`add_plot`. Do not add
721 directly edit this list.
722
723 :data:`plots` is a :class:`~kivy.properties.ListProperty`,
724 defaults to [].
725 '''
726
727
728 class Plot(EventDispatcher):
729 '''Plot class, see module documentation for more information.
730 '''
731
732 # this function is called by graph whenever any of the parameters
733 # change. The plot should be recalculated then.
734 # log, min, max indicate the axis settings.
735 # size a 4-tuple describing the bounding box in which we can draw
736 # graphs, it's (x0, y0, x1, y1), which correspond with the bottom left
737 # and top right corner locations, respectively.
738 def _update(self, xlog, xmin, xmax, ylog, ymin, ymax, size):
739 pass
740
741 # returns a string which is unique and is the group name given to all the
742 # instructions returned by _get_drawings. Graph uses this to remove
743 # these instructions when needed.
744 def _get_group(self):
745 return ''
746
747 # returns a list of canvas instructions that will be added to the graph's
748 # canvas. These instructions must belong to a group as described
749 # in _get_group.
750 def _get_drawings(self):
751 return []
752
753
754 class MeshLinePlot(Plot):
755 '''MeshLinePlot class which displays a set of points similar to a mesh.
756 '''
757
758 # mesh which forms the plot
759 _mesh = ObjectProperty(None)
760 # color of the plot
761 _color = ObjectProperty(None)
762 _trigger = ObjectProperty(None)
763 # most recent values of the params used to draw the plot
764 _params = DictProperty({'xlog': False, 'xmin': 0, 'xmax': 100,
765 'ylog': False, 'ymin': 0, 'ymax': 100,
766 'size': (0, 0, 0, 0)})
767
768 def __init__(self, **kwargs):
769 self._color = Color(1, 1, 1, group='LinePlot%d' % id(self))
770 self._mesh = Mesh(mode='line_strip', group='LinePlot%d' % id(self))
771 super().__init__(**kwargs)
772
773 self._trigger = Clock.create_trigger(self._redraw)
774 self.bind(_params=self._trigger, points=self._trigger)
775
776 def _update(self, xlog, xmin, xmax, ylog, ymin, ymax, size):
777 self._params = {'xlog': xlog, 'xmin': xmin, 'xmax': xmax, 'ylog': ylog,
778 'ymin': ymin, 'ymax': ymax, 'size': size}
779
780 def _redraw(self, *args):
781 points = self.points
782 mesh = self._mesh
783 vert = mesh.vertices
784 ind = mesh.indices
785 params = self._params
786 funcx = log10 if params['xlog'] else lambda x: x
787 funcy = log10 if params['ylog'] else lambda x: x
788 xmin = funcx(params['xmin'])
789 ymin = funcy(params['ymin'])
790 diff = len(points) - len(vert) / 4
791 size = params['size']
792 ratiox = (size[2] - size[0]) / float(funcx(params['xmax']) - xmin)
793 ratioy = (size[3] - size[1]) / float(funcy(params['ymax']) - ymin)
794 if diff < 0:
795 del vert[4 * len(points):]
796 del ind[len(points):]
797 elif diff > 0:
798 ind.extend(range(len(ind), len(ind) + diff))
799 vert.extend([0] * (diff * 4))
800 for k in range(len(points)):
801 vert[k * 4] = (funcx(points[k][0]) - xmin) * ratiox + size[0]
802 vert[k * 4 + 1] = (funcy(points[k][1]) - ymin) * ratioy + size[1]
803 mesh.vertices = vert
804
805 def _get_group(self):
806 return 'LinePlot%d' % id(self)
807
808 def _get_drawings(self):
809 return [self._color, self._mesh]
810
811 def _set_mode(self, value):
812 self._mesh.mode = value
813 mode = AliasProperty(lambda self: self._mesh.mode, _set_mode)
814 '''VBO Mode used for drawing the points. Can be one of: 'points',
815 'line_strip', 'line_loop', 'lines', 'triangle_strip', 'triangle_fan'.
816 See :class:`~kivy.graphics.Mesh` for more details.
817
818 Defaults to 'line_strip'.
819 '''
820
821 def _set_color(self, value):
822 self._color.rgba = value
823 color = AliasProperty(lambda self: self._color.rgba, _set_color)
824 '''Plot color, in the format [r, g, b, a] with values between 0-1.
825
826 Defaults to [1, 1, 1, 1].
827 '''
828
829 points = ListProperty([])
830 '''List of x, y points to be displayed in the plot.
831
832 The elements of points are 2-tuples, (x, y). The points are displayed
833 based on the mode setting.
834
835 :data:`points` is a :class:`~kivy.properties.ListProperty`, defaults to
836 [].
837 '''
838
839
840 class MeshStemPlot(MeshLinePlot):
841 '''MeshStemPlot uses the MeshLinePlot class to draw a stem plot. The data
842 provided is graphed from origin to the data point.
843 '''
844
845 def _redraw(self, *args):
846 points = self.points
847 mesh = self._mesh
848 self._mesh.mode = 'lines'
849 vert = mesh.vertices
850 ind = mesh.indices
851 params = self._params
852 funcx = log10 if params['xlog'] else lambda x: x
853 funcy = log10 if params['ylog'] else lambda x: x
854 xmin = funcx(params['xmin'])
855 ymin = funcy(params['ymin'])
856 diff = len(points) * 2 - len(vert) / 4
857 size = params['size']
858 ratiox = (size[2] - size[0]) / float(funcx(params['xmax']) - xmin)
859 ratioy = (size[3] - size[1]) / float(funcy(params['ymax']) - ymin)
860 if diff < 0:
861 del vert[4 * len(points):]
862 del ind[len(points):]
863 elif diff > 0:
864 ind.extend(range(len(ind), len(ind) + diff))
865 vert.extend([0] * (diff * 4))
866 for k in range(len(points)):
867 vert[k * 8] = (funcx(points[k][0]) - xmin) * ratiox + size[0]
868 vert[k * 8 + 1] = (0 - ymin) * ratioy + size[1]
869 vert[k * 8 + 4] = (funcx(points[k][0]) - xmin) * ratiox + size[0]
870 vert[k * 8 + 5] = (funcy(points[k][1]) - ymin) * ratioy + size[1]
871 mesh.vertices = vert
872
873
874 if __name__ == '__main__':
875 from math import sin, cos
876 from kivy.app import App
877
878 class TestApp(App):
879
880 def build(self):
881
882 graph = Graph(xlabel='Cheese', ylabel='Apples', x_ticks_minor=5,
883 x_ticks_major=25, y_ticks_major=1,
884 y_grid_label=True, x_grid_label=True, padding=5,
885 xlog=False, ylog=False, x_grid=True, y_grid=True,
886 xmin=-50, xmax=50, ymin=-1, ymax=1)
887 plot = MeshLinePlot(color=[1, 0, 0, 1])
888 plot.points = [(x / 10., sin(x / 50.)) for x in range(-500, 501)]
889 graph.add_plot(plot)
890 plot = MeshLinePlot(color=[0, 1, 0, 1])
891 plot.points = [(x / 10., cos(x / 50.)) for x in range(-600, 501)]
892 graph.add_plot(plot)
893 plot = MeshLinePlot(color=[0, 0, 1, 1])
894 graph.add_plot(plot)
895 plot.points = [(x, x / 50.) for x in range(-50, 51)]
896 return graph
897
898 TestApp().run()