12 PyX can be used for data and function plotting. At present x-y-graphs and
13 x-y-z-graphs are supported only. However, the component architecture of the
14 graph system described in section :ref:`graph_components` allows for additional
15 graph geometries while reusing most of the existing components.
17 Creating a graph splits into two basic steps. First you have to create a graph
18 instance. The most simple form would look like::
21 g = graph.graphxy(width=8)
23 The graph instance ``g`` created in this example can then be used to actually
24 plot something into the graph. Suppose you have some data in a file
25 :file:`graph.dat` you want to plot. The content of the file could look like:
28 .. include:: graph.dat
31 To plot these data into the graph ``g`` you must perform::
33 g.plot(graph.data.file("graph.dat", x=1, y=2))
35 The method :meth:`plot` takes the data to be plotted and optionally a list of
36 graph styles to be used to plot the data. When no styles are provided, a default
37 style defined by the data instance is used. For data read from a file by an
38 instance of :class:`graph.data.file`, the default are symbols. When
39 instantiating :class:`graph.data.file`, you not only specify the file name, but
40 also a mapping from columns to axis names and other information the styles might
41 make use of (*e.g.* data for error bars to be used by the errorbar style).
43 While the graph is already created by that, we still need to perform a write of
44 the result into a file. Since the graph instance is a canvas, we can just call
45 its :meth:`writeEPSfile` method. ::
47 g.writeEPSfile("graph")
49 The result :file:`graph.eps` is shown in figure :ref:`fig_graph`.
55 A minimalistic plot for the data from file :file:`graph.dat`.
57 Instead of plotting data from a file, other data source are available as well.
58 For example function data is created and placed into :meth:`plot` by the
61 g.plot(graph.data.function("y(x)=x**2"))
63 You can plot different data in a single graph by calling :meth:`plot` several
64 times before writing the output to a file. Note that a calling :meth:`plot`
65 will fail once a graph was forced to "finish" itself. This happens
66 automatically, when the graph is written to a file. Thus it is not an option to
67 call :meth:`plot` after writing the output. The topic of the finalization of a
68 graph is addressed in more detail in section :mod:`graph.graph`. As you can see
69 in figure :ref:`fig_graph2`, a function is plotted as a line by default.
75 Plotting data from a file together with a function.
77 While the axes ranges got adjusted automatically in the previous example, they
78 might be fixed by keyword options in axes constructors. Plotting only a function
79 will need such a setting at least in the variable coordinate. The following code
80 also shows how to set a logathmic axis in y-direction:
83 .. include:: graph3.py
86 The result is shown in figure :ref:`fig_graph3`.
92 Plotting a function for a given axis range and use a logarithmic y-axis.
97 Component architecture
98 ======================
100 Creating a graph involves a variety of tasks, which thus can be separated into
101 components without significant additional costs. This structure manifests itself
102 also in the PyX source, where there are different modules for the different
103 tasks. They interact by some well-defined interfaces. They certainly have to be
104 completed and stabilized in their details, but the basic structure came up in
105 the continuous development quite clearly. The basic parts of a graph are:
108 Defines the geometry of the graph by means of graph coordinates with range
109 [0:1]. Keeps lists of plotted data, axes *etc.*
112 Produces or prepares data to be plotted in graphs.
115 Performs the plotting of the data into the graph. It gets data, converts them
116 via the axes into graph coordinates and uses the graph to finally plot the data
117 with respect to the graph geometry methods.
120 Responsible for the graph keys.
123 Creates axes for the graph, which take care of the mapping from data values to
124 graph coordinates. Because axes are also responsible for creating ticks and
125 labels, showing up in the graph themselves and other things, this task is
126 splitted into several independent subtasks. Axes are discussed separately in
129 .. module:: graph.graph
131 Module :mod:`graph.graph`: Graph geometry
132 =========================================
135 The classes :class:`graphxy` and :class:`graphxyz` are part of the module
136 :mod:`graph.graph`. However, there are shortcuts to access the classes via
137 ``graph.graphxy`` and ``graph.graphxyz``, respectively.
140 .. class:: graphxy(xpos=0, ypos=0, width=None, height=None, ratio=goldenmean, key=None, backgroundattrs=None, axesdist=0.8*unit.v_cm, xaxisat=None, yaxisat=None, **axes)
142 This class provides an x-y-graph. A graph instance is also a fully functional
145 The position of the graph on its own canvas is specified by *xpos* and *ypos*.
146 The size of the graph is specified by *width*, *height*, and *ratio*. These
147 parameters define the size of the graph area not taking into account the
148 additional space needed for the axes. Note that you have to specify at least
149 *width* or *height*. *ratio* will be used as the ratio between *width* and
150 *height* when only one of these is provided.
152 *key* can be set to a :class:`graph.key.key` instance to create an automatic
153 graph key. ``None`` omits the graph key.
155 *backgroundattrs* is a list of attributes for drawing the background of the
156 graph. Allowed are decorators, strokestyles, and fillstyles. ``None`` disables
159 *axisdist* is the distance between axes drawn at the same side of a graph.
161 *xaxisat* and *yaxisat* specify a value at the y and x axis, where the
162 corresponding axis should be moved to. It's a shortcut for corresonding calls of
163 :meth:`axisatv` described below. Moving an axis by *xaxisat* or *yaxisat*
164 disables the automatic creation of a linked axis at the opposite side of the
167 *\*\*axes* receives axes instances. Allowed keywords (axes names) are ``x``,
168 ``x2``, ``x3``, *etc.* and ``y``, ``y2``, ``y3``, *etc.* When not providing an
169 ``x`` or ``y`` axis, linear axes instances will be used automatically. When not
170 providing a ``x2`` or ``y2`` axis, linked axes to the ``x`` and ``y`` axes are
171 created automatically and *vice versa*. As an exception, a linked axis is not
172 created automatically when the axis is placed at a specific position by
173 *xaxisat* or *yaxisat*. You can disable the automatic creation of axes by
174 setting the linked axes to ``None``. The even numbered axes are plotted at the
175 top (``x`` axes) and right (``y`` axes) while the others are plotted at the
176 bottom (``x`` axes) and left (``y`` axes) in ascending order each.
178 Some instance attributes might be useful for outside read-access. Those are:
181 .. attribute:: graphxy.axes
183 A dictionary mapping axes names to the :class:`anchoredaxis` instances.
185 To actually plot something into the graph, the following instance method
186 :meth:`plot` is provided:
189 .. method:: graphxy.plot(data, styles=None)
191 Adds *data* to the list of data to be plotted. Sets *styles* to be used for
192 plotting the data. When *styles* is ``None``, the default styles for the data as
193 provided by *data* is used.
195 *data* should be an instance of any of the data described in section
198 When the same combination of styles (*i.e.* the same references) are used
199 several times within the same graph instance, the styles are kindly asked by the
200 graph to iterate their appearance. Its up to the styles how this is performed.
202 Instead of calling the plot method several times with different *data* but the
203 same style, you can use a list (or something iterateable) for *data*.
205 While a graph instance only collects data initially, at a certain point it must
206 create the whole plot. Once this is done, further calls of :meth:`plot` will
207 fail. Usually you do not need to take care about the finalization of the graph,
208 because it happens automatically once you write the plot into a file. However,
209 sometimes position methods (described below) are nice to be accessible. For
210 that, at least the layout of the graph must have been finished. However, the
211 drawing order is based on canvas layers and thus the order in which the
212 :meth:`do`\ -methods are called will not alter the output. Multiple calls to
213 any of the :meth:`do`\ -methods have no effect (only the first call counts).
214 The orginal order in which the :meth:`do`\ -methods are called is:
217 .. method:: graphxy.dolayout()
219 Fixes the layout of the graph. As part of this work, the ranges of the axes are
220 fitted to the data when the axes ranges are allowed to adjust themselves to the
221 data ranges. The other :meth:`do`\ -methods ensure, that this method is always
225 .. method:: graphxy.dobackground()
227 Draws the background.
230 .. method:: graphxy.doaxes()
235 .. method:: graphxy.doplotitem(plotitem)
237 Plots the plotitem as returned by the graphs plot method.
240 .. method:: graphxy.doplot()
242 Plots all (remaining) plotitems.
245 .. method:: graphxy.dokeyitem()
247 Inserts a plotitem in the graph key as returned by the graphs plot method.
250 .. method:: graphxy.dokey()
252 Inserts the graph key.
255 .. method:: graphxy.finish()
257 Finishes the graph by calling all pending :meth:`do`\ -methods. This is done
258 automatically, when the output is created.
260 The graph provides some methods to access its geometry:
263 .. method:: graphxy.pos(x, y, xaxis=None, yaxis=None)
265 Returns the given point at *x* and *y* as a tuple ``(xpos, ypos)`` at the graph
266 canvas. *x* and *y* are anchoredaxis instances for the two axes *xaxis* and
267 *yaxis*. When *xaxis* or *yaxis* are ``None``, the axes with names ``x`` and
268 ``y`` are used. This method fails if called before :meth:`dolayout`.
271 .. method:: graphxy.vpos(vx, vy)
273 Returns the given point at *vx* and *vy* as a tuple ``(xpos, ypos)`` at the
274 graph canvas. *vx* and *vy* are graph coordinates with range [0:1].
277 .. method:: graphxy.vgeodesic(vx1, vy1, vx2, vy2)
279 Returns the geodesic between points *vx1*, *vy1* and *vx2*, *vy2* as a path. All
280 parameters are in graph coordinates with range [0:1]. For :class:`graphxy` this
284 .. method:: graphxy.vgeodesic_el(vx1, vy1, vx2, vy2)
286 Like :meth:`vgeodesic` but this method returns the path element to connect the
290 single: xbasepath()@xbasepath() (graphxy method)
291 single: xvbasepath()@xvbasepath() (graphxy method)
292 single: xgridpath()@xgridpath() (graphxy method)
293 single: xvgridpath()@xvgridpath() (graphxy method)
294 single: xtickpoint()@xtickpoint() (graphxy method)
295 single: xvtickpoint()@xvtickpoint() (graphxy method)
296 single: xtickdirection()@xtickdirection() (graphxy method)
297 single: xvtickdirection()@xvtickdirection() (graphxy method)
298 single: ybasepath()@ybasepath() (graphxy method)
299 single: yvbasepath()@yvbasepath() (graphxy method)
300 single: ygridpath()@ygridpath() (graphxy method)
301 single: yvgridpath()@yvgridpath() (graphxy method)
302 single: ytickpoint()@ytickpoint() (graphxy method)
303 single: yvtickpoint()@yvtickpoint() (graphxy method)
304 single: ytickdirection()@ytickdirection() (graphxy method)
305 single: yvtickdirection()@yvtickdirection() (graphxy method)
307 Further geometry information is available by the :attr:`axes` instance variable,
308 with is a dictionary mapping axis names to :class:`anchoredaxis` instances.
309 Shortcuts to the anchoredaxis positioner methods for the ``x``\ - and ``y``\
310 -axis become available after :meth:`dolayout` as :class:`graphxy` methods
311 ``Xbasepath``, ``Xvbasepath``, ``Xgridpath``, ``Xvgridpath``, ``Xtickpoint``,
312 ``Xvtickpoint``, ``Xtickdirection``, and ``Xvtickdirection`` where the prefix
313 ``X`` stands for ``x`` and ``y``.
316 .. method:: graphxy.axistrafo(axis, t)
318 This method can be used to apply a transformation *t* to an
319 :class:`anchoredaxis` instance *axis* to modify the axis position and the like.
320 This method fails when called on a not yet finished axis, i.e. it should be used
321 after :meth:`dolayout`.
324 .. method:: graphxy.axisatv(axis, v)
326 This method calls :meth:`axistrafo` with a transformation to move the axis
327 *axis* to a graph position *v* (in graph coordinates).
329 The class :class:`graphxyz` is very similar to the :class:`graphxy` class,
330 except for its additional dimension. In the following documentation only the
331 differences to the :class:`graphxy` class are described.
334 .. class:: graphxyz(xpos=0, ypos=0, size=None, xscale=1, yscale=1, zscale=1/goldenmean, xy12axesat=None, xy12axesatname="z", projector=central(10, -30, 30), key=None, **axes)
336 This class provides an x-y-z-graph.
338 The position of the graph on its own canvas is specified by *xpos* and *ypos*.
339 The size of the graph is specified by *size* and the length factors *xscale*,
340 *yscale*, and *zscale*. The final size of the graph depends on the projector
341 *projector*, which is called with ``x``, ``y``, and ``z`` values up to *xscale*,
342 *yscale*, and *zscale* respectively and scaling the result by *size*. For a
343 parallel projector changing *size* is thus identical to changing *xscale*,
344 *yscale*, and *zscale* by the same factor. For the central projector the
345 projectors internal distance would also need to be changed by this factor. Thus
346 *size* changes the size of the whole graph without changing the projection.
348 *xy12axesat* moves the xy-plane of the axes ``x``, ``x2``, ``y``, ``y2`` to the
349 given value at the axis *xy12axesatname*.
351 *projector* defines the conversion of 3d coordinates to 2d coordinates. It can
352 be an instance of :class:`central` or :class:`parallel` described below.
354 *\*\*axes* receives axes instances as for :class:`graphxy`. The graphxyz allows
355 for 4 axes per graph dimension ``x``, ``x2``, ``x3``, ``x4``, ``y``, ``y2``,
356 ``y3``, ``y4``, ``z``, ``z2``, ``z3``, and ``z4``. The x-y-plane is the
357 horizontal plane at the bottom and the ``x``, ``x2``, ``y``, and ``y2`` axes are
358 placed at the boundary of this plane with ``x`` and ``y`` always being in front.
359 ``x3``, ``x4``, ``y3``, and ``y4`` are handled similar, but for the top plane of
360 the graph. The ``z`` axis is placed at the origin of the ``x`` and ``y``
361 dimension, whereas ``z2`` is placed at the final point of the ``x`` dimension,
362 ``z3`` at the final point of the ``y`` dimension and ``z4`` at the final point
363 of the ``x`` and ``y`` dimension together.
366 .. attribute:: graphxyz.central
368 The central attribute of the graphxyz is the :class:`central` class. See the
369 class description below.
372 .. attribute:: graphxyz.parallel
374 The parallel attribute of the graphxyz is the :class:`parallel` class. See the
375 class description below.
377 Regarding the 3d to 2d transformation the methods :meth:`pos`, :meth:`vpos`,
378 :meth:`vgeodesic`, and :meth:`vgeodesic_el` are available as for class
379 :class:`graphxy` and just take an additional argument for the dimension. Note
380 that a similar transformation method (3d to 2d) is available as part of the
381 projector as well already, but only the graph acknowledges its size, the scaling
382 and the internal tranformation of the graph coordinates to the scaled
383 coordinates. As the projector also implements a :meth:`zindex` and a
384 :meth:`angle` method, those are also available at the graph level in the graph
385 coordinate variant (i.e. having an additional v in its name and using values
386 from 0 to 1 per dimension).
389 .. method:: graphxyz.vzindex(vx, vy, vz)
391 The depths of the point defined by *vx*, *vy*, and *vz* scaled to a range [-1:1]
392 where 1 is closest to the viewer. All arguments passed to the method are in graph
393 coordinates with range [0:1].
396 .. method:: graphxyz.vangle(vx1, vy1, vz1, vx2, vy2, vz2, vx3, vy3, vz3)
398 The cosine of the angle of the view ray thru point ``(vx1, vy1, vz1)`` and the
399 plane defined by the points ``(vx1, vy1, vz1)``, ``(vx2, vy2, vz2)``, and
400 ``(vx3, vy3, vz3)``. All arguments passed to the method are in graph coordinates
403 There are two projector classes :class:`central` and :class:`parallel`:
406 .. class:: central(distance, phi, theta, anglefactor=math.pi/180)
408 Instances of this class implement a central projection for the given parameters.
410 *distance* is the distance of the viewer from the origin. Note that the
411 :class:`graphxyz` class uses the range ``-xscale`` to ``xscale``, ``-yscale`` to
412 ``yscale``, and ``-zscale`` to ``zscale`` for the coordinates ``x``, ``y``, and
413 ``z``. As those scales are of the order of one (by default), the distance should
414 be of the order of 10 to give nice results. Smaller distances increase the
415 central projection character while for huge distances the central projection
416 becomes identical to the parallel projection.
418 ``phi`` is the angle of the viewer in the x-y-plane and ``theta`` is the angle
419 of the viewer to the x-y-plane. The standard notation for spheric coordinates
420 are used. The angles are multiplied by *anglefactor* which is initialized to do
421 a degree in radiant transformation such that you can specify ``phi`` and
422 ``theta`` in degree while the internal computation is always done in radiants.
425 .. class:: parallel(phi, theta, anglefactor=math.pi/180)
427 Instances of this class implement a parallel projection for the given
428 parameters. There is no distance for that transformation (compared to the
429 central projection). All other parameters are identical to the :class:`central`
433 .. module:: graph.data
435 Module :mod:`graph.data`: Graph data
436 ====================================
439 The following classes provide data for the :meth:`plot` method of a graph. The
440 classes are implemented in :mod:`graph.data`.
443 .. class:: file(filename, commentpattern=defaultcommentpattern, columnpattern=defaultcolumnpattern, stringpattern=defaultstringpattern, skiphead=0, skiptail=0, every=1, title=notitle, context={}, copy=1, replacedollar=1, columncallback="__column__", **columns)
445 This class reads data from a file and makes them available to the graph system.
446 *filename* is the name of the file to be read. The data should be organized in
449 The arguments *commentpattern*, *columnpattern*, and *stringpattern* are
450 responsible for identifying the data in each line of the file. Lines matching
451 *commentpattern* are ignored except for the column name search of the last non-
452 empty comment line before the data. By default a line starting with one of the
453 characters ``'#'``, ``'%'``, or ``'!'`` as well as an empty line is treated as a
456 A non-comment line is analysed by repeatedly matching *stringpattern* and,
457 whenever the stringpattern does not match, by *columnpattern*. When the
458 *stringpattern* matches, the result is taken as the value for the next column
459 without further transformations. When *columnpattern* matches, it is tried to
460 convert the result to a float. When this fails the result is taken as a string
461 as well. By default, you can write strings with spaces surrounded by ``'"'``
462 immediately surrounded by spaces or begin/end of line in the data file.
463 Otherwise ``'"'`` is not taken to be special.
465 *skiphead* and *skiptail* are numbers of data lines to be ignored at the
466 beginning and end of the file while *every* selects only every *every* line from
469 *title* is the title of the data to be used in the graph key. A default title is
470 constructed out of *filename* and *\*\*columns*. You may set *title* to ``None``
471 to disable the title.
473 Finally, *columns* define columns out of the existing columns from the file by a
474 column number or a mathematical expression (see below). When *copy* is set the
475 names of the columns in the file (file column names) and the freshly created
476 columns having the names of the dictionary key (data column names) are passed as
477 data to the graph styles. The data columns may hide file columns when names are
478 equal. For unset *copy* the file columns are not available to the graph styles.
480 File column names occur when the data file contains a comment line immediately
481 in front of the data (except for empty or empty comment lines). This line will
482 be parsed skipping the matched comment identifier as if the line would be
483 regular data, but it will not be converted to floats even if it would be
484 possible to convert the items. The result is taken as file column names, *i.e.*
485 a string representation for the columns in the file.
487 The values of *\*\*columns* can refer to column numbers in the file starting at
488 ``1``. The column ``0`` is also available and contains the line number starting
489 from ``1`` not counting comment lines, but lines skipped by *skiphead*,
490 *skiptail*, and *every*. Furthermore values of *\*\*columns* can be strings:
491 file column names or complex mathematical expressions. To refer to columns
492 within mathematical expressions you can also use file column names when they are
493 valid variable identifiers. Equal named items in context will then be hidden.
494 Alternatively columns can be access by the syntax ``$<number>`` when
495 *replacedollar* is set. They will be translated into function calls to
496 *columncallback*, which is a function to access column data by index or name.
498 *context* allows for accessing external variables and functions when evaluating
499 mathematical expressions for columns. Additionally to the identifiers in
500 *context*, the file column names, the *columncallback* function and the
501 functions shown in the table "builtins in math expressions" at the end of the
502 section are available.
506 graph.data.file("test.dat", a=1, b="B", c="2*B+$3")
508 with :file:`test.dat` looking like::
514 The columns with name ``"a"``, ``"b"``, ``"c"`` will become ``"[1.234,
515 5.678]"``, ``"[1.0, 3.0]"``, and ``"[4.0, 10.0]"``, respectively. The columns
516 ``"A"``, ``"B"``, ``"C"`` will be available as well, since *copy* is enabled by
519 When creating several data instances accessing the same file, the file is read
520 only once. There is an inherent caching of the file contents.
522 For the sake of completeness we list the default patterns:
525 .. attribute:: file.defaultcommentpattern
527 ``re.compile(r"(#+|!+|%+)\s*")``
530 .. attribute:: file.defaultcolumnpattern
532 ``re.compile(r"\"(.*?)\"(\s+|$)")``
535 .. attribute:: file.defaultstringpattern
537 ``re.compile(r"(.*?)(\s+|$)")``
540 .. class:: function(expression, title=notitle, min=None, max=None, points=100, context={})
542 This class creates graph data from a function. *expression* is the mathematical
543 expression of the function. It must also contain the result variable name
544 including the variable the function depends on by assignment. A typical example
545 looks like ``"y(x)=sin(x)"``.
547 *title* is the title of the data to be used in the graph key. By default
548 *expression* is used. You may set *title* to ``None`` to disable the title.
550 *min* and *max* give the range of the variable. If not set, the range spans the
551 whole axis range. The axis range might be set explicitly or implicitly by ranges
552 of other data. *points* is the number of points for which the function is
553 calculated. The points are choosen linearly in terms of graph coordinates.
555 *context* allows for accessing external variables and functions. Additionally to
556 the identifiers in *context*, the variable name and the functions shown in the
557 table "builtins in math expressions" at the end of the section are available.
560 .. class:: paramfunction(varname, min, max, expression, title=notitle, points=100, context={})
562 This class creates graph data from a parametric function. *varname* is the
563 parameter of the function. *min* and *max* give the range for that variable.
564 *points* is the number of points for which the function is calculated. The
565 points are choosen lineary in terms of the parameter.
567 *expression* is the mathematical expression for the parametric function. It
568 contains an assignment of a tuple of functions to a tuple of variables. A
569 typical example looks like ``"x, y = cos(k), sin(k)"``.
571 *title* is the title of the data to be used in the graph key. By default
572 *expression* is used. You may set *title* to ``None`` to disable the title.
574 *context* allows for accessing external variables and functions. Additionally to
575 the identifiers in *context*, *varname* and the functions shown in the table
576 "builtins in math expressions" at the end of the section are available.
579 .. class:: values(title="user provided values", **columns)
581 This class creates graph data from externally provided data. Each column is a
582 list of values to be used for that column.
584 *title* is the title of the data to be used in the graph key.
587 .. class:: points(data, title="user provided points", addlinenumbers=1, **columns)
589 This class creates graph data from externally provided data. *data* is a list of
590 lines, where each line is a list of data values for the columns.
592 *title* is the title of the data to be used in the graph key.
594 The keywords of *\*\*columns* become the data column names. The values are the
595 column numbers starting from one, when *addlinenumbers* is turned on (the zeroth
596 column is added to contain a line number in that case), while the column numbers
597 starts from zero, when *addlinenumbers* is switched off.
600 .. class:: data(data, title=notitle, context=, copy=1, replacedollar=1, columncallback="__column__", **columns)
602 This class provides graph data out of other graph data. *data* is the source of
603 the data. All other parameters work like the equally called parameters in
604 :class:`graph.data.file`. Indeed, the latter is built on top of this class by
605 reading the file and caching its contents in a :class:`graph.data.list`
609 .. class:: conffile(filename, title=notitle, context=, copy=1, replacedollar=1, columncallback="__column__", **columns)
611 This class reads data from a config file with the file name *filename*. The
612 format of a config file is described within the documentation of the
613 :mod:`ConfigParser` module of the Python Standard Library.
615 Each section of the config file becomes a data line. The options in a section
616 are the columns. The name of the options will be used as file column names. All
617 other parameters work as in *graph.data.file* and *graph.data.data* since they
618 all use the same code.
621 .. class:: cbdfile(filename, minrank=None, maxrank=None, title=notitle, context=, copy=1, replacedollar=1, columncallback="__column__", **columns)
623 This is an experimental class to read map data from cbd-files. See
624 `<http://sepwww.stanford.edu/ftp/World_Map/>`_ for some world-map data.
626 The builtins in math expressions are listed in the following table:
628 +------------------+--------------------------------------------+
630 +==================+============================================+
631 | ``neg`` | ``lambda x: -x`` |
632 +------------------+--------------------------------------------+
633 | ``abs`` | ``lambda x: x < 0 and -x or x`` |
634 +------------------+--------------------------------------------+
635 | ``sgn`` | ``lambda x: x < 0 and -1 or 1`` |
636 +------------------+--------------------------------------------+
637 | ``sqrt`` | ``math.sqrt`` |
638 +------------------+--------------------------------------------+
639 | ``exp`` | ``math.exp`` |
640 +------------------+--------------------------------------------+
641 | ``log`` | ``math.log`` |
642 +------------------+--------------------------------------------+
643 | ``sin`` | ``math.sin`` |
644 +------------------+--------------------------------------------+
645 | ``cos`` | ``math.cos`` |
646 +------------------+--------------------------------------------+
647 | ``tan`` | ``math.tan`` |
648 +------------------+--------------------------------------------+
649 | ``asin`` | ``math.asin`` |
650 +------------------+--------------------------------------------+
651 | ``acos`` | ``math.acos`` |
652 +------------------+--------------------------------------------+
653 | ``atan`` | ``math.atan`` |
654 +------------------+--------------------------------------------+
655 | ``sind`` | ``lambda x: math.sin(math.pi/180*x)`` |
656 +------------------+--------------------------------------------+
657 | ``cosd`` | ``lambda x: math.cos(math.pi/180*x)`` |
658 +------------------+--------------------------------------------+
659 | ``tand`` | ``lambda x: math.tan(math.pi/180*x)`` |
660 +------------------+--------------------------------------------+
661 | ``asind`` | ``lambda x: 180/math.pi*math.asin(x)`` |
662 +------------------+--------------------------------------------+
663 | ``acosd`` | ``lambda x: 180/math.pi*math.acos(x)`` |
664 +------------------+--------------------------------------------+
665 | ``atand`` | ``lambda x: 180/math.pi*math.atan(x)`` |
666 +------------------+--------------------------------------------+
667 | ``norm`` | ``lambda x, y: math.hypot(x, y)`` |
668 +------------------+--------------------------------------------+
669 | ``splitatvalue`` | see the ``splitatvalue`` description below |
670 +------------------+--------------------------------------------+
671 | ``pi`` | ``math.pi`` |
672 +------------------+--------------------------------------------+
673 | ``e`` | ``math.e`` |
674 +------------------+--------------------------------------------+
676 ``math`` refers to Pythons :mod:`math` module. The ``splitatvalue`` function is
680 .. function:: splitatvalue(value, *splitpoints)
682 This method returns a tuple ``(section, value)``. The section is calculated by
683 comparing *value* with the values of splitpoints. If *splitpoints* contains only
684 a single item, ``section`` is ``0`` when value is lower or equal this item and
685 ``1`` else. For multiple splitpoints, ``section`` is ``0`` when its lower or
686 equal the first item, ``None`` when its bigger than the first item but lower or
687 equal the second item, ``1`` when its even bigger the second item, but lower or
688 equal the third item. It continues to alter between ``None`` and ``2``, ``3``,
692 .. module:: graph.style
694 Module :mod:`graph.style`: Graph styles
695 =======================================
697 Please note that we are talking about graph styles here. Those are responsible
698 for plotting symbols, lines, bars and whatever else into a graph. Do not mix it
699 up with path styles like the line width, the line style (solid, dashed, dotted
702 The following classes provide styles to be used at the :meth:`plot` method of a
703 graph. The plot method accepts a list of styles. By that you can combine several
704 styles at the very same time.
706 Some of the styles below are hidden styles. Those do not create any output, but
707 they perform internal data handling and thus help on modularization of the
708 styles. Usually, a visible style will depend on data provided by one or more
709 hidden styles but most of the time it is not necessary to specify the hidden
710 styles manually. The hidden styles register themself to be the default for
711 providing certain internal data.
714 .. class:: pos(usenames={}, epsilon=1e-10)
716 This class is a hidden style providing a position in the graph. It needs a data
717 column for each graph dimension. For that the column names need to be equal to
718 an axis name, or a name translation from axis names to column names need to be
719 given by *usenames*. Data points are considered to be out of graph when their
720 position in graph coordinates exceeds the range [0:1] by more than *epsilon*.
723 .. class:: range(usenames={}, epsilon=1e-10)
725 This class is a hidden style providing an errorbar range. It needs data column
726 names constructed out of a axis name ``X`` for each dimension errorbar data
727 should be provided as follows:
729 +-----------+---------------------------+
730 | data name | description |
731 +===========+===========================+
732 | ``Xmin`` | minimal value |
733 +-----------+---------------------------+
734 | ``Xmax`` | maximal value |
735 +-----------+---------------------------+
736 | ``dX`` | minimal and maximal delta |
737 +-----------+---------------------------+
738 | ``dXmin`` | minimal delta |
739 +-----------+---------------------------+
740 | ``dXmax`` | maximal delta |
741 +-----------+---------------------------+
743 When delta data are provided the style will also read column data for the axis
744 name ``X`` itself. *usenames* allows to insert a translation dictionary from
745 axis names to the identifiers ``X``.
747 *epsilon* is a comparison precision when checking for invalid errorbar ranges.
750 .. class:: symbol(symbol=changecross, size=0.2*unit.v_cm, symbolattrs=[])
752 This class is a style for plotting symbols in a graph. *symbol* refers to a
753 (changeable) symbol function with the prototype ``symbol(c, x_pt, y_pt, size_pt,
754 attrs)`` and draws the symbol into the canvas ``c`` at the position ``(x_pt,
755 y_pt)`` with size ``size_pt`` and attributes ``attrs``. Some predefined symbols
756 are available in member variables listed below. The symbol is drawn at size
757 *size* using *symbolattrs*. *symbolattrs* is merged with ``defaultsymbolattrs``
758 which is a list containing the decorator :class:`deco.stroked`. An instance of
759 :class:`symbol` is the default style for all graph data classes described in
760 section :mod:`graph.data` except for :class:`function` and
761 :class:`paramfunction`.
763 The class :class:`symbol` provides some symbol functions as member variables,
767 .. attribute:: symbol.cross
769 A cross. Should be used for stroking only.
772 .. attribute:: symbol.plus
774 A plus. Should be used for stroking only.
777 .. attribute:: symbol.square
779 A square. Might be stroked or filled or both.
782 .. attribute:: symbol.triangle
784 A triangle. Might be stroked or filled or both.
787 .. attribute:: symbol.circle
789 A circle. Might be stroked or filled or both.
792 .. attribute:: symbol.diamond
794 A diamond. Might be stroked or filled or both.
796 :class:`symbol` provides some changeable symbol functions as member variables,
800 .. attribute:: symbol.changecross
802 attr.changelist([cross, plus, square, triangle, circle, diamond])
805 .. attribute:: symbol.changeplus
807 attr.changelist([plus, square, triangle, circle, diamond, cross])
810 .. attribute:: symbol.changesquare
812 attr.changelist([square, triangle, circle, diamond, cross, plus])
815 .. attribute:: symbol.changetriangle
817 attr.changelist([triangle, circle, diamond, cross, plus, square])
820 .. attribute:: symbol.changecircle
822 attr.changelist([circle, diamond, cross, plus, square, triangle])
825 .. attribute:: symbol.changediamond
827 attr.changelist([diamond, cross, plus, square, triangle, circle])
830 .. attribute:: symbol.changesquaretwice
832 attr.changelist([square, square, triangle, triangle, circle, circle, diamond,
836 .. attribute:: symbol.changetriangletwice
838 attr.changelist([triangle, triangle, circle, circle, diamond, diamond, square,
842 .. attribute:: symbol.changecircletwice
844 attr.changelist([circle, circle, diamond, diamond, square, square, triangle,
848 .. attribute:: symbol.changediamondtwice
850 attr.changelist([diamond, diamond, square, square, triangle, triangle, circle,
853 The class :class:`symbol` provides two changeable decorators for alternated
854 filling and stroking. Those are especially useful in combination with the
855 :meth:`change`\ -\ :meth:`twice`\ -symbol methods above. They are:
858 .. attribute:: symbol.changestrokedfilled
860 attr.changelist([deco.stroked, deco.filled])
863 .. attribute:: symbol.changefilledstroked
865 attr.changelist([deco.filled, deco.stroked])
868 .. class:: line(lineattrs=[], epsilon=1e-10)
870 This class is a style to stroke lines in a graph. *lineattrs* is merged with
871 ``defaultlineattrs`` which is a list containing the member variable
872 ``changelinestyle`` as described below. An instance of :class:`line` is the
873 default style of the graph data classes :class:`function` and
874 :class:`paramfunction` described in section :mod:`graph.data`. *epsilon* is
875 a precision in graph coordinates for line clipping.
877 The class :class:`line` provides a changeable line style. Its definition is:
880 .. attribute:: line.changelinestyle
882 attr.changelist([style.linestyle.solid, style.linestyle.dashed,
883 style.linestyle.dotted, style.linestyle.dashdotted])
886 .. class:: impulses(lineattrs=[], fromvalue=0, frompathattrs=[], valueaxisindex=1)
888 This class is a style to plot impulses. *lineattrs* is merged with
889 ``defaultlineattrs`` which is a list containing the member variable
890 ``changelinestyle`` of the :class:`line` class. *fromvalue* is the baseline
891 value of the impulses. When set to ``None``, the impulses will start at the
892 baseline. When fromvalue is set, *frompathattrs* are the stroke attributes used
893 to show the impulses baseline path.
896 .. class:: errorbar(size=0.1*unit.v_cm, errorbarattrs=[], epsilon=1e-10)
898 This class is a style to stroke errorbars in a graph. *size* is the size of the
899 caps of the errorbars and *errorbarattrs* are the stroke attributes. Errorbars
900 and error caps are considered to be out of the graph when their position in
901 graph coordinates exceeds the range [0:1] by more that *epsilon*. Out of graph
902 caps are omitted and the errorbars are cut to the valid graph range.
905 .. class:: text(textname="text", dxname=None, dyname=None, dxunit=0.3*unit.v_cm, dyunit=0.3*unit.v_cm, textdx=0*unit.v_cm, textdy=0.3*unit.v_cm, textattrs=[])
907 This class is a style to stroke text in a graph. The text to be written has to
908 be provided in the data column named ``textname``. *textdx* and *textdy* are the
909 position of the text with respect to the position in the graph. Alternatively
910 you can specify a ``dxname`` and a ``dyname`` and provide appropriate data in
911 those columns to be taken in units of *dxunit* and *dyunit* to specify the
912 position of the text for each point separately. *textattrs* are text attributes
913 for the output of the text. Those attributes are merged with the default
914 attributes ``textmodule.halign.center`` and ``textmodule.vshift.mathaxis``.
917 .. class:: arrow(linelength=0.25*unit.v_cm, arrowsize=0.15*unit.v_cm, lineattrs=[], arrowattrs=[], arrowpos=0.5, epsilon=1e-10, decorator=deco.earrow)
919 This class is a style to plot short lines with arrows into a two-dimensional
920 graph to a given graph position. The arrow parameters are defined by two
921 additional data columns named ``size`` and ``angle`` define the size and angle
922 for each arrow. ``size`` is taken as a factor to *arrowsize* and *linelength*,
923 the size of the arrow and the length of the line the arrow is plotted at.
924 ``angle`` is the angle the arrow points to with respect to a horizontal line.
925 The ``angle`` is taken in degrees and used in mathematically positive sense.
926 *lineattrs* and *arrowattrs* are styles for the arrow line and arrow head,
927 respectively. *arrowpos* defines the position of the arrow line with respect to
928 the position at the graph. The default ``0.5`` means centered at the graph
929 position, whereas ``0`` and ``1`` creates the arrows to start or end at the
930 graph position, respectively. *epsilon* is used as a cutoff for short arrows in
931 order to prevent numerical instabilities. *decorator* defines the decorator to
932 be added to the line.
935 .. class:: rect(colorname="color", gradient=color.gradient.Grey, coloraxis=None, keygraph=_autokeygraph)
937 This class is a style to plot colored rectangles into a two-dimensional graph.
938 The size of the rectangles is taken from the data provided by the :class:`range`
939 style. The additional data column named *colorname* specifies the color of the
940 rectangle defined by *gradient*. The translation of the data values to the
941 gradient is done by the *coloraxis*, which is set to be a linear axis if not
942 provided by *coloraxis*. A key graph, a graphx instance, is generated
943 automatically to indicate the color scale if not provided by *keygraph*.
944 If a *keygraph* is given, its ``x`` axis defines the color conversion and
945 *coloraxis* is ignored.
948 .. class:: histogram(lineattrs=[], steps=0, fromvalue=0, frompathattrs=[], fillable=0, rectkey=0, autohistogramaxisindex=0, autohistogrampointpos=0.5, epsilon=1e-10)
950 This class is a style to plot histograms. *lineattrs* is merged with
951 ``defaultlineattrs`` which is ``[deco.stroked]``. When *steps* is set, the
952 histrogram is plotted as steps instead of the default being a boxed histogram.
953 *fromvalue* is the baseline value of the histogram. When set to ``None``, the
954 histogram will start at the baseline. When fromvalue is set, *frompathattrs* are
955 the stroke attributes used to show the histogram baseline path.
957 The *fillable* flag changes the stoke line of the histogram to make it fillable
958 properly. This is important on non-steped histograms or on histograms, which hit
959 the graph boundary. *rectkey* can be set to generate a rectanglar area instead
960 of a line in the graph key.
962 In the most general case, a histogram is defined by a range specification (like
963 for an errorbar) in one graph dimension (say, along the x-axis) and a value for
964 the other graph dimension. This allows for the widths of the histogram boxes
965 being variable. Often, however, all histogram bin ranges are equally sized, and
966 instead of passing the range, the position of the bin along the x-axis fully
967 specifies the histogram - assuming that there are at least two bins. This common
968 case is supported via two parameters: *autohistogramaxisindex*, which defines
969 the index of the independent histogram axis (in the case just described this
970 would be ``0`` designating the x axis). *autohistogrampointpos*, defines the
971 relative position of the center of the histogram bin: ``0.5`` means that the bin
972 is centered at the values passed to the style, ``0`` (``1``) means that the bin
973 is aligned at the right-(left-)hand side.
975 XXX describe, how to specify general histograms with varying bin widths
977 Positions of the histograms are considered to be out of graph when they exceed
978 the graph coordinate range [0:1] by more than *epsilon*.
981 .. class:: barpos(fromvalue=None, frompathattrs=[], epsilon=1e-10)
983 This class is a hidden style providing position information in a bar graph.
984 Those graphs need to contain a specialized axis, namely a bar axis. The data
985 column for this bar axis is named ``Xname`` where ``X`` is an axis name. In the
986 other graph dimension the data column name must be equal to an axis name. To
987 plot several bars in a single graph side by side, you need to have a nested bar
988 axis and provide a tuple as data for nested bar axis.
990 The bars start at *fromvalue* when provided. The *fromvalue* is marked by a
991 gridline stroked using *frompathattrs*. Thus this hidden style might actually
992 create some output. The value of a bar axis is considered to be out of graph
993 when its position in graph coordinates exceeds the range [0:1] by more than
997 .. class:: stackedbarpos(stackname, addontop=0, epsilon=1e-10)
999 This class is a hidden style providing position information in a bar graph by
1000 stacking a new bar on top of another bar. The value of the new bar is taken from
1001 the data column named *stackname*. When *addontop* is set, the values is taken
1002 relative to the previous top of the bar.
1005 .. class:: bar(barattrs=[], epsilon=1e-10, gradient=color.gradient.RedBlack)
1007 This class draws bars in a bar graph. The bars are filled using *barattrs*.
1008 *barattrs* is merged with ``defaultbarattrs`` which is a list containing
1009 ``[color.gradient.Rainbow, deco.stroked([color.grey.black])]``.
1011 The bar style has limited support for 3d graphs: Occlusion does not work
1012 properly on stacked bars or multiple dataset. *epsilon* is used in 3d to prevent
1013 numerical instabilities on bars without hight. When *gradient* is not ``None``
1014 it is used to calculate a lighting coloring taking into account the angle
1015 between the view ray and the bar and the distance between viewer and bar. The
1016 precise conversion is defined in the :meth:`lighting` method.
1019 .. class:: changebar(barattrs=[])
1021 This style works like the :class:`bar` style, but instead of the *barattrs* to
1022 be changed on subsequent data instances the *barattrs* are changed for each
1023 value within a single data instance. In the result the style can't be applied to
1024 several data instances and does not support 3d. The style raises an error
1028 .. class:: gridpos(index1=0, index2=1, gridlines1=1, gridlines2=1, gridattrs=[], epsilon=1e-10)
1030 This class is a hidden style providing rectangular grid information out of graph
1031 positions for graph dimensions *index1* and *index2*. Data points are considered
1032 to be out of graph when their position in graph coordinates exceeds the range
1033 [0:1] by more than *epsilon*. Data points are merged to a single graph
1034 coordinate value when their difference in graph coordinates is below *epsilon*.
1037 .. class:: grid(gridlines1=1, gridlines2=1, gridattrs=[], epsilon=1e-10)
1039 Strokes a rectangular grid in the first grid direction, when *gridlines1* is set
1040 and in the second grid direction, when *gridlines2* is set. *gridattrs* is
1041 merged with ``defaultgridattrs`` which is a list containing the member variable
1042 ``changelinestyle`` of the :class:`line` class. *epsilon* is a precision in graph
1043 coordinates for line clipping.
1046 .. class:: surface(gridlines1=0.05, gridlines2=0.05, gridcolor=None, backcolor=color.gray.black, **kwargs)
1048 Draws a surface of a rectangular grid. Each rectangle is divided into 4
1051 If a *gridcolor* is set, the rectangular grid is marked by small stripes of the
1052 relative (compared to each rectangle) size of *gridlines1* and *gridlines2* for
1053 the first and second grid direction, respectively.
1055 *backcolor* is used to fill triangles shown from the back. If *backcolor* is set
1056 to ``None``, back sides are not drawn differently from the front sides.
1058 The surface is encoded using a single mesh. While this is quite space efficient,
1059 it has the following implications:
1061 * All colors must use the same color space.
1063 * HSB colors are not allowed, whereas Gray, RGB, and CMYK are allowed. You can
1064 convert HSB colors into a different color space by means of
1065 :class:`rgbgradient` and class:`cmykgradient` before passing it to the
1068 * The grid itself is also constructed out of triangles. The grid is transformed
1069 along with the triangles thus looking quite different from a stroked grid (as
1070 done by the grid style).
1072 * Occlusion is handled by proper painting order.
1074 * Color changes are continuous (in the selected color space) for each triangle.
1076 Further arguments are identical to the :class:`graph.style.rect` style. However,
1077 if no *colorname* column exists, the surface style falls back to a lighting
1078 coloring taking into account the angle between the view ray and the triangle and
1079 the distance between viewer and triangle. The precise conversion is defined in
1080 the :meth:`lighting` method.
1083 .. class:: density(epsilon=1e-10, **kwargs):
1085 Density plots can be created by the density style. It is similar to a surface
1086 plot in 2d, but it does not use a mesh, but a bitmap representation instead.
1087 Due to that difference, the file size is smaller and no color interpolation
1088 takes place. Furthermore the style can be used with equidistantly spaced data
1089 only (after conversion by the axis, so logarithmic raw data and such are
1090 possible using proper axes). Further arguments are identical to the
1091 :class:`graph.style.rect` style.
1094 .. module:: graph.key
1096 Module :mod:`graph.key`: Graph keys
1097 ===================================
1099 The following class provides a key, whose instances can be passed to the
1100 constructor keyword argument ``key`` of a graph. The class is implemented in
1104 .. class:: key(dist=0.2*unit.v_cm, pos="tr", hpos=None, vpos=None, hinside=1, vinside=1, hdist=0.6*unit.v_cm, vdist=0.4*unit.v_cm, symbolwidth=0.5*unit.v_cm, symbolheight=0.25*unit.v_cm, symbolspace=0.2*unit.v_cm, textattrs=[], columns=1, columndist=0.5*unit.v_cm, border=0.3*unit.v_cm, keyattrs=None)
1106 This class writes the title of the data in a plot together with a small
1107 illustration of the style. The style is responsible for its illustration.
1109 *dist* is a visual length and a distance between the key entries. *pos* is the
1110 position of the key with respect to the graph. Allowed values are combinations
1111 of ``"t"`` (top), ``"m"`` (middle) and ``"b"`` (bottom) with ``"l"`` (left),
1112 ``"c"`` (center) and ``"r"`` (right). Alternatively, you may use *hpos* and
1113 *vpos* to specify the relative position using the range [0:1]. *hdist* and
1114 *vdist* are the distances from the specified corner of the graph. *hinside* and
1115 *vinside* are numbers to be set to 0 or 1 to define whether the key should be
1116 placed horizontally and vertically inside of the graph or not.
1118 *symbolwidth* and *symbolheight* are passed to the style to control the size of
1119 the style illustration. *symbolspace* is the space between the illustration and
1120 the text. *textattrs* are attributes for the text creation. They are merged with
1121 ``[text.vshift.mathaxis]``.
1123 *columns* is a number of columns of the graph key and *columndist* is the
1124 distance between those columns.
1126 When *keyattrs* is set to contain some draw attributes, the graph key is
1127 enlarged by *border* and the key area is drawn using *keyattrs*.