Graph

kivy_garden.graph

Graph

The Graph widget is a widget for displaying plots. It supports drawing multiple plot with different colors on the Graph. It also supports axes titles, ticks, labeled ticks, grids and a log or linear representation on both the x and y axis, independently.

To display a plot. First create a graph which will function as a “canvas” for the plots. Then create plot objects e.g. MeshLinePlot and add them to the graph.

To create a graph with x-axis between 0-100, y-axis between -1 to 1, x and y labels of and X and Y, respectively, x major and minor ticks every 25, 5 units, respectively, y major ticks every 1 units, full x and y grids and with a red line plot containing a sin wave on this range:

from kivy_garden.graph import Graph, MeshLinePlot
graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5,
              x_ticks_major=25, y_ticks_major=1,
              y_grid_label=True, x_grid_label=True, padding=5,
              x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1)
plot = MeshLinePlot(color=[1, 0, 0, 1])
plot.points = [(x, sin(x / 10.)) for x in range(0, 101)]
graph.add_plot(plot)

The MeshLinePlot plot is a particular plot which draws a set of points using a mesh object. The points are given as a list of tuples, with each tuple being a (x, y) coordinate in the graph’s units.

You can create different types of plots other than MeshLinePlot by inheriting from the Plot class and implementing the required functions. The Graph object provides a “canvas” to which a Plot’s instructions are added. The plot object is responsible for updating these instructions to show within the bounding box of the graph the proper plot. The Graph notifies the Plot when it needs to be redrawn due to changes. See the MeshLinePlot class for how it is done.

The current availables plots are:

  • MeshStemPlot

  • MeshLinePlot

  • SmoothLinePlot - require Kivy 1.8.1

Note

The graph uses a stencil view to clip the plots to the graph display area. As with the stencil graphics instructions, you cannot stack more than 8 stencil-aware widgets.

class kivy_garden.graph.Graph(**kwargs)

Bases: kivy.uix.widget.Widget

Graph class, see module documentation for more information.

add_plot(plot)

Add a new plot to this graph.

Parameters
plot:

Plot to add to this graph.

>>> graph = Graph()
>>> plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1])
>>> plot.points = [(x / 10., sin(x / 50.)) for x in range(-0, 101)]
>>> graph.add_plot(plot)
add_widget(widget)

Add a new widget as a child of this widget.

Parameters
widget: Widget

Widget to add to our list of children.

index: int, defaults to 0

Index to insert the widget in the list. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. For a full discussion of the index and widget hierarchy, please see the Widgets Programming Guide.

New in version 1.0.5.

canvas: str, defaults to None

Canvas to add widget’s canvas to. Can be ‘before’, ‘after’ or None for the default canvas.

New in version 1.9.0.

>>> from kivy.uix.button import Button
>>> from kivy.uix.slider import Slider
>>> root = Widget()
>>> root.add_widget(Button())
>>> slider = Slider()
>>> root.add_widget(slider)
add_x_axis(xmin, xmax, xlog=False)
add_y_axis(ymin, ymax, ylog=False)
background_color

Color of the background, defaults to transparent

border_color

Color of the border, defaults to white

collide_plot(x, y)

Determine if the given coordinates fall inside the plot area. Use x, y = self.to_widget(x, y, relative=True) to first convert into widget coordinates if it’s in window coordinates because it’s assumed to be given in local widget coordinates, relative to the graph’s pos.

Parameters
x, y:

The coordinates to test.

draw_border

Whether a border is drawn around the canvas of the graph where the plots are displayed.

draw_border is a BooleanProperty, defaults to True.

font_size

Font size of the labels.

font_size is a NumericProperty, defaults to 15sp.

get_x_axis(axis=0)
get_y_axis(axis=0)
label_options

Label options that will be passed to :class:`kivy.uix.Label.

padding

Padding distances between the labels, axes titles and graph, as well between the widget and the objects near the boundaries.

padding is a NumericProperty, defaults to 5dp.

plots

Holds a list of all the plots in the graph. To add and remove plots from the graph use add_plot and add_plot. Do not add directly edit this list.

plots is a ListProperty, defaults to [].

precision

Determines the numerical precision of the tick mark labels. This value governs how the numbers are converted into string representation. Accepted values are those listed in Python’s manual in the “String Formatting Operations” section.

precision is a StringProperty, defaults to ‘%g’.

remove_plot(plot)

Remove a plot from this graph.

Parameters
plot:

Plot to remove from this graph.

>>> graph = Graph()
>>> plot = MeshLinePlot(mode='line_strip', color=[1, 0, 0, 1])
>>> plot.points = [(x / 10., sin(x / 50.)) for x in range(-0, 101)]
>>> graph.add_plot(plot)
>>> graph.remove_plot(plot)
remove_widget(widget)

Remove a widget from the children of this widget.

Parameters
widget: Widget

Widget to remove from our children list.

>>> from kivy.uix.button import Button
>>> root = Widget()
>>> button = Button()
>>> root.add_widget(button)
>>> root.remove_widget(button)
tick_color

Color of the grid/ticks, default to 1/4. grey.

to_data(x, y)

Convert widget coords to data coords. Use x, y = self.to_widget(x, y, relative=True) to first convert into widget coordinates if it’s in window coordinates because it’s assumed to be given in local widget coordinates, relative to the graph’s pos.

Parameters
x, y:

The coordinates to convert.

If the graph has multiple axes, use Plot.unproject instead.

view_pos

The pos of the graph viewing area - the area where the plots are displayed, excluding labels etc. It is relative to the graph’s pos.

view_size

The size of the graph viewing area - the area where the plots are displayed, excluding labels etc.

x_axis

ListProperty(defaultvalue=0, **kw) Property that represents a list.

Parameters
defaultvalue: list, defaults to []

Specifies the default value of the property.

Warning

When assigning a list to a ListProperty, the list stored in the property is a shallow copy of the list and not the original list. This can be demonstrated with the following example:

>>> class MyWidget(Widget):
>>>     my_list = ListProperty([])

>>> widget = MyWidget()
>>> my_list = [1, 5, {'hi': 'hello'}]
>>> widget.my_list = my_list
>>> print(my_list is widget.my_list)
False
>>> my_list.append(10)
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'hello'}, 10] [1, 5, {'hi': 'hello'}]

However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.

>>> my_list[2]['hi'] = 'bye'
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'bye'}, 10] [1, 5, {'hi': 'bye'}]
x_grid

Determines whether the x-axis has tick marks or a full grid.

If x_ticks_major is non-zero, then if x_grid is False tick marks will be displayed at every major tick. If x_grid is True, instead of ticks, a vertical line will be displayed at every major tick.

x_grid is a BooleanProperty, defaults to False.

x_grid_label

Whether labels should be displayed beneath each major tick. If true, each major tick will have a label containing the axis value.

x_grid_label is a BooleanProperty, defaults to False.

x_ticks_angle

Rotate angle of the x-axis tick marks.

x_ticks_angle is a NumericProperty, defaults to 0.

x_ticks_major

Distance between major tick marks on the x-axis.

Determines the distance between the major tick marks. Major tick marks start from min and re-occur at every ticks_major until xmax. If xmax doesn’t overlap with a integer multiple of ticks_major, no tick will occur at xmax. Zero indicates no tick marks.

If xlog is true, then this indicates the distance between ticks in multiples of current decade. E.g. if xmin is 0.1 and ticks_major is 0.1, it means there will be a tick at every 10th of the decade, i.e. 0.1 … 0.9, 1, 2… If it is 0.3, the ticks will occur at 0.1, 0.3, 0.6, 0.9, 2, 5, 8, 10. You’ll notice that it went from 8 to 10 instead of to 20, that’s so that we can say 0.5 and have ticks at every half decade, e.g. 0.1, 0.5, 1, 5, 10, 50… Similarly, if ticks_major is 1.5, there will be ticks at 0.1, 5, 100, 5,000… Also notice, that there’s always a major tick at the start. Finally, if e.g. xmin is 0.6 and this 0.5 there will be ticks at 0.6, 1, 5…

x_ticks_major is a BoundedNumericProperty, defaults to 0.

x_ticks_minor

The number of sub-intervals that divide x_ticks_major.

Determines the number of sub-intervals into which ticks_major is divided, if non-zero. The actual number of minor ticks between the major ticks is ticks_minor - 1. Only used if ticks_major is non-zero. If there’s no major tick at xmax then the number of minor ticks after the last major tick will be however many ticks fit until xmax.

If self.xlog is true, then this indicates the number of intervals the distance between major ticks is divided. The result is the number of multiples of decades between ticks. I.e. if ticks_minor is 10, then if ticks_major is 1, there will be ticks at 0.1, 0.2…0.9, 1, 2, 3… If ticks_major is 0.3, ticks will occur at 0.1, 0.12, 0.15, 0.18… Finally, as is common, if ticks major is 1, and ticks minor is 5, there will be ticks at 0.1, 0.2, 0.4… 0.8, 1, 2…

x_ticks_minor is a BoundedNumericProperty, defaults to 0.

xlabel

The label for the x-axis. If not empty it is displayed in the center of the axis.

xlabel is a StringProperty, defaults to ‘’.

xlog

Determines whether the x-axis should be displayed logarithmically (True) or linearly (False).

xlog is a BooleanProperty, defaults to False.

xmax

The x-axis maximum value, larger than xmin.

xmax is a NumericProperty, defaults to 0.

xmin

The x-axis minimum value.

If xlog is True, xmin must be larger than zero.

xmin is a NumericProperty, defaults to 0.

y_axis

ListProperty(defaultvalue=0, **kw) Property that represents a list.

Parameters
defaultvalue: list, defaults to []

Specifies the default value of the property.

Warning

When assigning a list to a ListProperty, the list stored in the property is a shallow copy of the list and not the original list. This can be demonstrated with the following example:

>>> class MyWidget(Widget):
>>>     my_list = ListProperty([])

>>> widget = MyWidget()
>>> my_list = [1, 5, {'hi': 'hello'}]
>>> widget.my_list = my_list
>>> print(my_list is widget.my_list)
False
>>> my_list.append(10)
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'hello'}, 10] [1, 5, {'hi': 'hello'}]

However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.

>>> my_list[2]['hi'] = 'bye'
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'bye'}, 10] [1, 5, {'hi': 'bye'}]
y_grid

Determines whether the y-axis has tick marks or a full grid. See x_grid.

y_grid is a BooleanProperty, defaults to False.

y_grid_label

Whether labels should be displayed beneath each major tick. If true, each major tick will have a label containing the axis value.

y_grid_label is a BooleanProperty, defaults to False.

y_ticks_major

Distance between major tick marks. See x_ticks_major.

y_ticks_major is a BoundedNumericProperty, defaults to 0.

y_ticks_minor

The number of sub-intervals that divide ticks_major. See x_ticks_minor.

y_ticks_minor is a BoundedNumericProperty, defaults to 0.

ylabel

The label for the y-axis. If not empty it is displayed in the center of the axis.

ylabel is a StringProperty, defaults to ‘’.

ylog

Determines whether the y-axis should be displayed logarithmically (True) or linearly (False).

ylog is a BooleanProperty, defaults to False.

ymax

The y-axis maximum value, larger than ymin.

ymax is a NumericProperty, defaults to 0.

ymin

The y-axis minimum value.

If ylog is True, ymin must be larger than zero.

ymin is a NumericProperty, defaults to 0.

class kivy_garden.graph.Plot(**kwargs)

Bases: kivy._event.EventDispatcher

Plot class, see module documentation for more information.

Events
on_clear_plot

Fired before a plot updates the display and lets the fbo know that it should clear the old drawings.

..versionadded:: 0.4

color

Color of the plot.

create_drawings()

called once to create all the canvas instructions needed for the plot

draw(*largs)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

funcx()

Return a function that convert or not the X value according to plot prameters

funcy()

Return a function that convert or not the Y value according to plot prameters

get_drawings()

returns a list of canvas instructions that will be added to the graph’s canvas.

get_group()

returns a string which is unique and is the group name given to all the instructions returned by _get_drawings. Graph uses this to remove these instructions when needed.

get_px_bounds()

Returns a dict containing the pixels bounds from the plot parameters. The returned values are relative to the graph pos.

iterate_points()

Iterate on all the points adjusted to the graph settings

on_clear_plot(*largs)
params

DictProperty(defaultvalue=0, rebind=False, **kw) Property that represents a dict.

Parameters
defaultvalue: dict, defaults to {}

Specifies the default value of the property.

rebind: bool, defaults to False

See ObjectProperty for details.

Changed in version 1.9.0: rebind has been introduced.

Warning

Similar to ListProperty, when assigning a dict to a DictProperty, the dict stored in the property is a shallow copy of the dict and not the original dict. See ListProperty for details.

points

List of (x, y) points to be displayed in the plot.

The elements of points are 2-tuples, (x, y). The points are displayed based on the mode setting.

points is a ListProperty, defaults to [].

unproject(x, y)

Return a function that unproject a pixel to a X/Y value on the plot (works only for linear, not log yet). x, y, is relative to the graph pos, so the graph’s pos needs to be subtracted from x, y before passing it in.

update(xlog, xmin, xmax, ylog, ymin, ymax, size)

Called by graph whenever any of the parameters change. The plot should be recalculated then. log, min, max indicate the axis settings. size a 4-tuple describing the bounding box in which we can draw graphs, it’s (x0, y0, x1, y1), which correspond with the bottom left and top right corner locations, respectively.

x_axis

Index of the X axis to use, defaults to 0

x_px()

Return a function that convert the X value of the graph to the pixel coordinate on the plot, according to the plot settings and axis settings. It’s relative to the graph pos.

y_axis

Index of the Y axis to use, defaults to 0

y_px()

Return a function that convert the Y value of the graph to the pixel coordinate on the plot, according to the plot settings and axis settings. The returned value is relative to the graph pos.

class kivy_garden.graph.MeshLinePlot(**kwargs)

Bases: kivy_garden.graph.Plot

MeshLinePlot class which displays a set of points similar to a mesh.

create_drawings()

called once to create all the canvas instructions needed for the plot

draw(*args)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

mode

VBO Mode used for drawing the points. Can be one of: ‘points’, ‘line_strip’, ‘line_loop’, ‘lines’, ‘triangle_strip’, ‘triangle_fan’. See Mesh for more details.

Defaults to ‘line_strip’.

plot_mesh()
set_mesh_size(size)
class kivy_garden.graph.MeshStemPlot(**kwargs)

Bases: kivy_garden.graph.MeshLinePlot

MeshStemPlot uses the MeshLinePlot class to draw a stem plot. The data provided is graphed from origin to the data point.

plot_mesh()
class kivy_garden.graph.LinePlot(**kwargs)

Bases: kivy_garden.graph.Plot

LinePlot draws using a standard Line object.

create_drawings()

called once to create all the canvas instructions needed for the plot

draw(*args)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

line_width

NumericProperty(defaultvalue=0, **kw) Property that represents a numeric value.

Parameters
defaultvalue: int or float, defaults to 0

Specifies the default value of the property.

>>> wid = Widget()
>>> wid.x = 42
>>> print(wid.x)
42
>>> wid.x = "plop"
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "properties.pyx", line 93, in kivy.properties.Property.__set__
   File "properties.pyx", line 111, in kivy.properties.Property.set
   File "properties.pyx", line 159, in kivy.properties.NumericProperty.check
 ValueError: NumericProperty accept only int/float

Changed in version 1.4.1: NumericProperty can now accept custom text and tuple value to indicate a type, like “in”, “pt”, “px”, “cm”, “mm”, in the format: ‘10pt’ or (10, ‘pt’).

on_line_width(*largs)
class kivy_garden.graph.SmoothLinePlot(**kwargs)

Bases: kivy_garden.graph.Plot

Smooth Plot class, see module documentation for more information. This plot use a specific Fragment shader for a custom anti aliasing.

GRADIENT_DATA = b"\x00\x00\x00\x07\x07\x07\x0f\x0f\x0f\x17\x17\x17\x1f\x1f\x1f'''///777???GGGOOOWWW___gggooowww\x7f\x7f\x7f\x87\x87\x87\x8f\x8f\x8f\x97\x97\x97\x9f\x9f\x9f\xa7\xa7\xa7\xaf\xaf\xaf\xb7\xb7\xb7\xbf\xbf\xbf\xc7\xc7\xc7\xcf\xcf\xcf\xd7\xd7\xd7\xdf\xdf\xdf\xe7\xe7\xe7\xef\xef\xef\xf7\xf7\xf7\xff\xff\xff\xf6\xf6\xf6\xee\xee\xee\xe6\xe6\xe6\xde\xde\xde\xd5\xd5\xd5\xcd\xcd\xcd\xc5\xc5\xc5\xbd\xbd\xbd\xb4\xb4\xb4\xac\xac\xac\xa4\xa4\xa4\x9c\x9c\x9c\x94\x94\x94\x8b\x8b\x8b\x83\x83\x83{{{sssjjjbbbZZZRRRJJJAAA999111))) \x18\x18\x18\x10\x10\x10\x08\x08\x08\x00\x00\x00"
SMOOTH_FS = '\n $HEADER$\n\n void main(void) {\n float edgewidth = 0.015625 * 64.;\n float t = texture2D(texture0, tex_coord0).r;\n float e = smoothstep(0., edgewidth, t);\n gl_FragColor = frag_color * vec4(1, 1, 1, e);\n }\n '
create_drawings()

called once to create all the canvas instructions needed for the plot

draw(*args)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

class kivy_garden.graph.ContourPlot(**kwargs)

Bases: kivy_garden.graph.Plot

ContourPlot visualizes 3 dimensional data as an intensity map image. The user must first specify ‘xrange’ and ‘yrange’ (tuples of min,max) and then ‘data’, the intensity values. data, is a MxN matrix, where the first dimension of size M specifies the y values, and the second dimension of size N specifies the x values. Axis Y and X values are assumed to be linearly spaced values from xrange/yrange and the dimensions of ‘data’, MxN, respectively. The color values are automatically scaled to the min and max z range of the data set.

create_drawings()

called once to create all the canvas instructions needed for the plot

data

ObjectProperty(defaultvalue=None, rebind=False, **kw) Property that represents a Python object.

Parameters
defaultvalue: object type

Specifies the default value of the property.

rebind: bool, defaults to False

Whether kv rules using this object as an intermediate attribute in a kv rule, will update the bound property when this object changes.

That is the standard behavior is that if there’s a kv rule text: self.a.b.c.d, where a, b, and c are properties with rebind False and d is a StringProperty. Then when the rule is applied, text becomes bound only to d. If a, b, or c change, text still remains bound to d. Furthermore, if any of them were None when the rule was initially evaluated, e.g. b was None; then text is bound to b and will not become bound to d even when b is changed to not be None.

By setting rebind to True, however, the rule will be re-evaluated and all the properties rebound when that intermediate property changes. E.g. in the example above, whenever b changes or becomes not None if it was None before, text is evaluated again and becomes rebound to d. The overall result is that text is now bound to all the properties among a, b, or c that have rebind set to True.

**kwargs: a list of keyword arguments
baseclass

If kwargs includes a baseclass argument, this value will be used for validation: isinstance(value, kwargs[‘baseclass’]).

Warning

To mark the property as changed, you must reassign a new python object.

Changed in version 1.9.0: rebind has been introduced.

Changed in version 1.7.0: baseclass parameter added.

draw(*args)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

xrange

ListProperty(defaultvalue=0, **kw) Property that represents a list.

Parameters
defaultvalue: list, defaults to []

Specifies the default value of the property.

Warning

When assigning a list to a ListProperty, the list stored in the property is a shallow copy of the list and not the original list. This can be demonstrated with the following example:

>>> class MyWidget(Widget):
>>>     my_list = ListProperty([])

>>> widget = MyWidget()
>>> my_list = [1, 5, {'hi': 'hello'}]
>>> widget.my_list = my_list
>>> print(my_list is widget.my_list)
False
>>> my_list.append(10)
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'hello'}, 10] [1, 5, {'hi': 'hello'}]

However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.

>>> my_list[2]['hi'] = 'bye'
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'bye'}, 10] [1, 5, {'hi': 'bye'}]
yrange

ListProperty(defaultvalue=0, **kw) Property that represents a list.

Parameters
defaultvalue: list, defaults to []

Specifies the default value of the property.

Warning

When assigning a list to a ListProperty, the list stored in the property is a shallow copy of the list and not the original list. This can be demonstrated with the following example:

>>> class MyWidget(Widget):
>>>     my_list = ListProperty([])

>>> widget = MyWidget()
>>> my_list = [1, 5, {'hi': 'hello'}]
>>> widget.my_list = my_list
>>> print(my_list is widget.my_list)
False
>>> my_list.append(10)
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'hello'}, 10] [1, 5, {'hi': 'hello'}]

However, changes to nested levels will affect the property as well, since the property uses a shallow copy of my_list.

>>> my_list[2]['hi'] = 'bye'
>>> print(my_list, widget.my_list)
[1, 5, {'hi': 'bye'}, 10] [1, 5, {'hi': 'bye'}]
class kivy_garden.graph.ScatterPlot(**kwargs)

Bases: kivy_garden.graph.Plot

ScatterPlot draws using a standard Point object. The pointsize can be controlled with point_size.

>>> plot = ScatterPlot(color=[1, 0, 0, 1], point_size=5)
create_drawings()

called once to create all the canvas instructions needed for the plot

draw(*args)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

on_point_size(*largs)
point_size

The point size of the scatter points. Defaults to 1.

class kivy_garden.graph.PointPlot(**kwargs)

Bases: kivy_garden.graph.Plot

Displays a set of points.

create_drawings()

called once to create all the canvas instructions needed for the plot

draw(*args)

draw the plot according to the params. It dispatches on_clear_plot so derived classes should call super before updating.

point_size

Defaults to 1.