Description¶
This module can be used to create high-quality, presentation-ready X-Y graphs quickly and easily
Class hierarchy¶
The properties of the graph (figure in Matplotlib parlance) are defined in an object of the pplot.Figure class.
Each figure can have one or more panels, whose properties are defined by objects of the pplot.Panel class. Panels are arranged vertically in the figure and share the same independent axis. The limits of the independent axis of the figure result from the union of the limits of the independent axis of all the panels. The independent axis is shown by default in the bottom-most panel although it can be configured to be in any panel or panels.
Each panel can have one or more data series, whose properties are defined by objects of the pplot.Series class. A series can be associated with either the primary or secondary dependent axis of the panel. The limits of the primary and secondary dependent axis of the panel result from the union of the primary and secondary dependent data points of all the series associated with each axis. The primary axis is shown on the left of the panel and the secondary axis is shown on the right of the panel. Axes can be linear or logarithmic.
The data for a series is defined by a source. Two data sources are provided:
the pplot.BasicSource class provides basic data validation
and minimum/maximum independent variable range bounding. The
pplot.CsvSource class builds upon the functionality of the
pplot.BasicSource class and offers a simple way of accessing
data from a comma-separated values (CSV) file. Other data sources can be
programmed by inheriting from the pplot.functions.DataSource
abstract base class (ABC). The custom data source needs to implement the
following methods: __str__
, _set_indep_var
and
_set_dep_var
. The latter two methods set the contents of the
independent variable (an increasing real Numpy vector) and the dependent
variable (a real Numpy vector) of the source, respectively.
Figure 1: Example diagram of the class hierarchy of a figure. In this particular example the figure consists of 3 panels. Panel 1 has a series whose data comes from a basic source, panel 2 has three series, two of which come from comma-separated values (CSV) files and one that comes from a basic source. Panel 3 has one series whose data comes from a basic source.
Axes tick marks¶
Axes tick marks are selected so as to create the most readable graph. Two global variables control the actual number of ticks, pplot.constants.MIN_TICKS and pplot.constants.SUGGESTED_MAX_TICKS. In general the number of ticks are between these two bounds; one or two more ticks can be present if a data series uses interpolation and the interpolated curve goes above (below) the largest (smallest) data point. Tick spacing is chosen so as to have the most number of data points “on grid”. Engineering notation (i.e. 1K = 1000, 1m = 0.001, etc.) is used for the axis tick marks.
Example¶
# plot_example_1.py
from __future__ import print_function
import os
import sys
import matplotlib
import numpy
import pplot
def main(fname, no_print):
"""
Example of how to use the pplot library
to generate presentation-quality plots
"""
###
# Series definition (Series class)
###
# Extract data from a comma-separated (csv)
# file using the CsvSource class
wdir = os.path.dirname(__file__)
csv_file = os.path.join(wdir, 'data.csv')
series1_obj = [pplot.Series(
data_source=pplot.CsvSource(
fname=csv_file,
rfilter={'value1':1},
indep_col_label='value2',
dep_col_label='value3',
indep_min=None,
indep_max=None,
fproc=series1_proc_func,
fproc_eargs={'xoffset':1e-3}
),
label='Source 1',
color='k',
marker='o',
interp='CUBIC',
line_style='-',
secondary_axis=False
)]
# Literal data can be used with the BasicSource class
series2_obj = [pplot.Series(
data_source=pplot.BasicSource(
indep_var=numpy.array([0e-3, 1e-3, 2e-3]),
dep_var=numpy.array([4, 7, 8]),
),
label='Source 2',
color='r',
marker='s',
interp='STRAIGHT',
line_style='--',
secondary_axis=False
)]
series3_obj = [pplot.Series(
data_source=pplot.BasicSource(
indep_var=numpy.array([0.5e-3, 1e-3, 1.5e-3]),
dep_var=numpy.array([10, 9, 6]),
),
label='Source 3',
color='b',
marker='h',
interp='STRAIGHT',
line_style='--',
secondary_axis=True
)]
series4_obj = [pplot.Series(
data_source=pplot.BasicSource(
indep_var=numpy.array([0.3e-3, 1.8e-3, 2.5e-3]),
dep_var=numpy.array([8, 8, 8]),
),
label='Source 4',
color='g',
marker='D',
interp='STRAIGHT',
line_style=None,
secondary_axis=True
)]
###
# Panels definition (Panel class)
###
panel_obj = pplot.Panel(
series=series1_obj+series2_obj+series3_obj+series4_obj,
primary_axis_label='Primary axis label',
primary_axis_units='-',
secondary_axis_label='Secondary axis label',
secondary_axis_units='W',
legend_props={'pos':'lower right', 'cols':1}
)
###
# Figure definition (Figure class)
###
fig_obj = pplot.Figure(
panels=panel_obj,
indep_var_label='Indep. var.',
indep_var_units='S',
log_indep_axis=False,
fig_width=4*2.25,
fig_height=3*2.25,
title='Library pplot Example'
)
# Save figure
output_fname = os.path.join(wdir, fname)
if not no_print:
print('Saving image to file {0}'.format(output_fname))
fig_obj.save(output_fname)
def series1_proc_func(indep_var, dep_var, xoffset):
""" Process data 1 series """
return (indep_var*1e-3)-xoffset, dep_var
case | value1 | value2 | value3 |
---|---|---|---|
0 | 0 | 1 | 3 |
1 | 0 | 2 | 3 |
2 | 1 | 1 | 3.5 |
3 | 1 | 2 | 5.75 |
4 | 1 | 3 | 10.11 |
5 | 1 | 4 | 8.88 |
6 | 2 | 1 | 1 |
7 | 2 | 2 | 3 |
Figure 2: plot_example_1.png generated by plot_example_1.py
Interpreter¶
The package has been developed and tested with Python 2.6, 2.7, 3.3, 3.4 and 3.5 under Linux (Debian, Ubuntu), Apple OS X and Microsoft Windows
Installing¶
$ pip install pplot
Documentation¶
Available at Read the Docs
Contributing¶
Abide by the adopted code of conduct
Fork the repository from GitHub and then clone personal copy [1]:
$ git clone \ https://github.com/[github-user-name]/pplot.git Cloning into 'pplot'... ... $ cd pplot $ export PPLOT_DIR=${PWD}
Install the project’s Git hooks and build the documentation. The pre-commit hook does some minor consistency checks, namely trailing whitespace and PEP8 compliance via Pylint. Assuming the directory to which the repository was cloned is in the
$PPLOT_DIR
shell environment variable:$ ${PPLOT_DIR}/sbin/complete-cloning.sh Installing Git hooks Building pplot package documentation ...
Ensure that the Python interpreter can find the package modules (update the
$PYTHONPATH
environment variable, or use sys.paths(), etc.)$ export PYTHONPATH=${PYTHONPATH}:${PPLOT_DIR}
Install the dependencies (if needed, done automatically by pip):
- Astroid (Python 2.6: older than 1.4, Python 2.7 or newer: 1.3.8 or newer)
- Cog (2.4 or newer)
- Coverage (3.7.1 or newer)
- Decorator (3.4.2 or newer)
- Docutils (0.12 or newer)
- Funcsigs (Python 2.x only, 0.4 or newer)
- Inline Syntax Highlight Sphinx Extension (0.2 or newer)
- Matplotlib (1.4.1 or newer)
- Mock (Python 2.x only, 1.0.1 or newer)
- Nose (Python 2.6: 1.0.0 or newer)
- Numpy (1.8.2 or newer)
- Pcsv (1.0.0 or newer)
- Peng (1.0.0 or newer)
- Pexdoc (1.0.0 or newer)
- Pillow (2.6.1 or newer)
- Pmisc (1.0.0 or newer)
- Py.test (2.7.0 or newer)
- PyContracts (1.7.2 or newer except 1.7.7)
- PyParsing (2.0.7 or newer)
- Pylint (Python 2.6: 1.3 or newer and older than 1.4, Python 2.7 or newer: 1.3.1 or newer)
- Pytest-coverage (1.8.0 or newer)
- Pytest-xdist (optional, 1.8.0 or newer)
- ReadTheDocs Sphinx theme (0.1.9 or newer)
- Scipy (0.13.3 or newer)
- Six (1.4.0 or newer)
- Sphinx (1.2.3 or newer)
- Tox (1.9.0 or newer)
- Virtualenv (13.1.2 or newer)
Implement a new feature or fix a bug
Write a unit test which shows that the contributed code works as expected. Run the package tests to ensure that the bug fix or new feature does not have adverse side effects. If possible achieve 100% code and branch coverage of the contribution. Thorough package validation can be done via Tox and Py.test:
$ tox GLOB sdist-make: .../pplot/setup.py py26-pkg inst-nodeps: .../pplot/.tox/dist/pplot-...zip
Setuptools can also be used (Tox is configured as its virtual environment manager) [2]:
$ python setup.py tests running tests running egg_info writing requirements to pplot.egg-info/requires.txt writing pplot.egg-info/PKG-INFO ...
Tox (or Setuptools via Tox) runs with the following default environments:
py26-pkg
,py27-pkg
,py33-pkg
,py34-pkg
andpy35-pkg
[3]. These use the Python 2.6, 2.7, 3.3, 3.4 and 3.5 interpreters, respectively, to test all code in the documentation (both in Sphinx*.rst
source files and in docstrings), run all unit tests, measure test coverage and re-build the exceptions documentation. To pass arguments to Py.test (the test runner) use a double dash (--
) after all the Tox arguments, for example:$ tox -e py27-pkg -- -n 4 GLOB sdist-make: .../pplot/setup.py py27-pkg inst-nodeps: .../pplot/.tox/dist/pplot-...zip ...
Or use the
-a
Setuptools optional argument followed by a quoted string with the arguments for Py.test. For example:$ python setup.py tests -a "-e py27-pkg -- -n 4" running tests ...
There are other convenience environments defined for Tox [4]:
py26-repl
,py27-repl
,py33-repl
,py34-repl
andpy35-repl
run the Python 2.6, 2.7, 3.3, 3.4 or 3.5 REPL, respectively, in the appropriate virtual environment. Thepplot
package is pip-installed by Tox when the environments are created. Arguments to the interpreter can be passed in the command line after a double dash (--
)py26-test
,py27-test
,py33-test
,py34-test
andpy35-test
run py.test using the Python 2.6, 2.7, 3.3, 3.4 or Python 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
) , for example:$ tox -e py34-test -- -x test_pplot.py GLOB sdist-make: [...]/pplot/setup.py py34-test inst-nodeps: [...]/pplot/.tox/dist/pplot-[...].zip py34-test runtests: PYTHONHASHSEED='680528711' py34-test runtests: commands[0] | [...]py.test -x test_pplot.py ===================== test session starts ===================== platform linux -- Python 3.4.2 -- py-1.4.30 -- [...] ...
py26-cov
,py27-cov
,py33-cov
,py34-cov
andpy35-cov
test code and branch coverage using the Python 2.6, 2.7, 3.3, 3.4 or 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
). The report can be found in${PPLOT_DIR}/.tox/py[PV]/usr/share/pplot/tests/htmlcov/index.html
where[PV]
stands for26
,27
,33
,34
or35
depending on the interpreter used
Verify that continuous integration tests pass. The package has continuous integration configured for Linux (via Travis) and for Microsoft Windows (via Appveyor). Aggregation/cloud code coverage is configured via Codecov. It is assumed that the Codecov repository upload token in the Travis build is stored in the
${CODECOV_TOKEN}
environment variable (securely defined in the Travis repository settings page). Travis build artifacts can be transferred to Dropbox using the Dropbox Uploader script (included for convenience in the${PPLOT_DIR}/sbin
directory). For an automatic transfer that does not require manual entering of authentication credentials place the APPKEY, APPSECRET, ACCESS_LEVEL, OAUTH_ACCESS_TOKEN and OAUTH_ACCESS_TOKEN_SECRET values required by Dropbox Uploader in the in the${DBU_APPKEY}
,${DBU_APPSECRET}
,${DBU_ACCESS_LEVEL}
,${DBU_OAUTH_ACCESS_TOKEN}
and${DBU_OAUTH_ACCESS_TOKEN_SECRET}
environment variables, respectively (also securely defined in Travis repository settings page)Document the new feature or bug fix (if needed). The script
${PPLOT_DIR}/sbin/build_docs.py
re-builds the whole package documentation (re-generates images, cogs source files, etc.):$ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] Build pplot package documentation optional arguments: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY specify source file directory (default ../pplot) -r, --rebuild rebuild exceptions documentation. If no module name is given all modules with auto-generated exceptions documentation are rebuilt -n NUM_CPUS, --num-cpus NUM_CPUS number of CPUs to use (default: 1) -t, --test diff original and rebuilt file(s) (exit code 0 indicates file(s) are identical, exit code 1 indicates file(s) are different)
Output of shell commands can be automatically included in reStructuredText source files with the help of Cog and the
docs.support.term_echo
module.-
docs.support.term_echo.
ste
(command, nindent, mdir, fpointer) Simplified terminal echo; prints STDOUT resulting from a given Bash shell command (relative to the package
sbin
directory) formatted in reStructuredTextParameters: - command (string) – Bash shell command, relative to
${PUTIL_DIR}/sbin
- nindent (integer) – Indentation level
- mdir (string) – Module directory
- fpointer (function object) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging
For example:
.. This is a reStructuredText file snippet .. [[[cog .. import os, sys .. from docs.support.term_echo import term_echo .. file_name = sys.modules['docs.support.term_echo'].__file__ .. mdir = os.path.realpath( .. os.path.dirname( .. os.path.dirname(os.path.dirname(file_name)) .. ) .. ) .. [[[cog ste('build_docs.py -h', 0, mdir, cog.out) ]]] .. code-block:: bash $ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] [module_name [module_name ...]] ... .. ]]]
- command (string) – Bash shell command, relative to
-
docs.support.term_echo.
term_echo
(command, nindent=0, env=None, fpointer=None, cols=60) Terminal echo; prints STDOUT resulting from a given Bash shell command formatted in reStructuredText
Parameters: - command (string) – Bash shell command
- nindent (integer) – Indentation level
- env (dictionary) – Environment variable replacement dictionary. The Bash
command is pre-processed and any environment variable
represented in the full notation (
${...}
) is replaced. The dictionary key is the environment variable name and the dictionary value is the replacement value. For example, if command is'${PYTHON_CMD} -m "x=5"'
and env is{'PYTHON_CMD':'python3'}
the actual command issued is'python3 -m "x=5"'
- fpointer (function object) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging - cols (integer) – Number of columns of output
Similarly Python files can be included in docstrings with the help of Cog and the
docs.support.incfile
module-
docs.support.incfile.
incfile
(fname, fpointer, lrange='1, 6-', sdir=None) Includes a Python source file in a docstring formatted in reStructuredText
Parameters: - fname (string) – File name, relative to environment variable
${TRACER_DIR}
- fpointer (function object) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging - lrange (string) – Line range to include, similar to Sphinx literalinclude directive
- sdir (string) – Source file directory. If None the
${TRACER_DIR}
environment variable is used if it is defined, otherwise the directory where thedocs.support.incfile
module is located is used
For example:
def func(): """ This is a docstring. This file shows how to use it: .. =[=cog .. import docs.support.incfile .. docs.support.incfile.incfile('func_example.py', cog.out) .. =]= .. code-block:: python # func_example.py if __name__ == '__main__': func() .. =[=end=]= """ return 'This is func output'
- fname (string) – File name, relative to environment variable
-
Footnotes
[1] | All examples are for the bash shell |
[2] | It appears that Scipy dependencies do not include Numpy (as they should) so running the tests via Setuptools will typically result in an error. The pplot requirement file specifies Numpy before Scipy and this installation order is honored by Tox so running the tests via Tox sidesteps Scipy’s broken dependency problem but requires Tox to be installed before running the tests (Setuptools installs Tox if needed) |
[3] | It is assumed that all the Python interpreters are in the executables path. Source code for the interpreters can be downloaded from Python’s main site |
[4] | Tox configuration largely inspired by Ionel’s codelog |
Changelog¶
- 1.0.0 [2016-05-12]: Final release of 1.0.0 branch
- 1.0.0rc1 [2016-05-12]: Initial commit, forked a subset from putil PyPI package
License¶
The MIT License (MIT)
Copyright (c) 2013-2016 Pablo Acosta-Serafini
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Contents¶
Description¶
This module can be used to create high-quality, presentation-ready X-Y graphs quickly and easily
Class hierarchy¶
The properties of the graph (figure in Matplotlib parlance) are defined in an object of the pplot.Figure class.
Each figure can have one or more panels, whose properties are defined by objects of the pplot.Panel class. Panels are arranged vertically in the figure and share the same independent axis. The limits of the independent axis of the figure result from the union of the limits of the independent axis of all the panels. The independent axis is shown by default in the bottom-most panel although it can be configured to be in any panel or panels.
Each panel can have one or more data series, whose properties are defined by objects of the pplot.Series class. A series can be associated with either the primary or secondary dependent axis of the panel. The limits of the primary and secondary dependent axis of the panel result from the union of the primary and secondary dependent data points of all the series associated with each axis. The primary axis is shown on the left of the panel and the secondary axis is shown on the right of the panel. Axes can be linear or logarithmic.
The data for a series is defined by a source. Two data sources are provided:
the pplot.BasicSource class provides basic data validation
and minimum/maximum independent variable range bounding. The
pplot.CsvSource class builds upon the functionality of the
pplot.BasicSource class and offers a simple way of accessing
data from a comma-separated values (CSV) file. Other data sources can be
programmed by inheriting from the pplot.functions.DataSource
abstract base class (ABC). The custom data source needs to implement the
following methods: __str__
, _set_indep_var
and
_set_dep_var
. The latter two methods set the contents of the
independent variable (an increasing real Numpy vector) and the dependent
variable (a real Numpy vector) of the source, respectively.
Figure 1: Example diagram of the class hierarchy of a figure. In this particular example the figure consists of 3 panels. Panel 1 has a series whose data comes from a basic source, panel 2 has three series, two of which come from comma-separated values (CSV) files and one that comes from a basic source. Panel 3 has one series whose data comes from a basic source.
Axes tick marks¶
Axes tick marks are selected so as to create the most readable graph. Two global variables control the actual number of ticks, pplot.constants.MIN_TICKS and pplot.constants.SUGGESTED_MAX_TICKS. In general the number of ticks are between these two bounds; one or two more ticks can be present if a data series uses interpolation and the interpolated curve goes above (below) the largest (smallest) data point. Tick spacing is chosen so as to have the most number of data points “on grid”. Engineering notation (i.e. 1K = 1000, 1m = 0.001, etc.) is used for the axis tick marks.
Example¶
# plot_example_1.py
from __future__ import print_function
import os
import sys
import matplotlib
import numpy
import pplot
def main(fname, no_print):
"""
Example of how to use the pplot library
to generate presentation-quality plots
"""
###
# Series definition (Series class)
###
# Extract data from a comma-separated (csv)
# file using the CsvSource class
wdir = os.path.dirname(__file__)
csv_file = os.path.join(wdir, 'data.csv')
series1_obj = [pplot.Series(
data_source=pplot.CsvSource(
fname=csv_file,
rfilter={'value1':1},
indep_col_label='value2',
dep_col_label='value3',
indep_min=None,
indep_max=None,
fproc=series1_proc_func,
fproc_eargs={'xoffset':1e-3}
),
label='Source 1',
color='k',
marker='o',
interp='CUBIC',
line_style='-',
secondary_axis=False
)]
# Literal data can be used with the BasicSource class
series2_obj = [pplot.Series(
data_source=pplot.BasicSource(
indep_var=numpy.array([0e-3, 1e-3, 2e-3]),
dep_var=numpy.array([4, 7, 8]),
),
label='Source 2',
color='r',
marker='s',
interp='STRAIGHT',
line_style='--',
secondary_axis=False
)]
series3_obj = [pplot.Series(
data_source=pplot.BasicSource(
indep_var=numpy.array([0.5e-3, 1e-3, 1.5e-3]),
dep_var=numpy.array([10, 9, 6]),
),
label='Source 3',
color='b',
marker='h',
interp='STRAIGHT',
line_style='--',
secondary_axis=True
)]
series4_obj = [pplot.Series(
data_source=pplot.BasicSource(
indep_var=numpy.array([0.3e-3, 1.8e-3, 2.5e-3]),
dep_var=numpy.array([8, 8, 8]),
),
label='Source 4',
color='g',
marker='D',
interp='STRAIGHT',
line_style=None,
secondary_axis=True
)]
###
# Panels definition (Panel class)
###
panel_obj = pplot.Panel(
series=series1_obj+series2_obj+series3_obj+series4_obj,
primary_axis_label='Primary axis label',
primary_axis_units='-',
secondary_axis_label='Secondary axis label',
secondary_axis_units='W',
legend_props={'pos':'lower right', 'cols':1}
)
###
# Figure definition (Figure class)
###
fig_obj = pplot.Figure(
panels=panel_obj,
indep_var_label='Indep. var.',
indep_var_units='S',
log_indep_axis=False,
fig_width=4*2.25,
fig_height=3*2.25,
title='Library pplot Example'
)
# Save figure
output_fname = os.path.join(wdir, fname)
if not no_print:
print('Saving image to file {0}'.format(output_fname))
fig_obj.save(output_fname)
def series1_proc_func(indep_var, dep_var, xoffset):
""" Process data 1 series """
return (indep_var*1e-3)-xoffset, dep_var
case | value1 | value2 | value3 |
---|---|---|---|
0 | 0 | 1 | 3 |
1 | 0 | 2 | 3 |
2 | 1 | 1 | 3.5 |
3 | 1 | 2 | 5.75 |
4 | 1 | 3 | 10.11 |
5 | 1 | 4 | 8.88 |
6 | 2 | 1 | 1 |
7 | 2 | 2 | 3 |
Figure 2: plot_example_1.png generated by plot_example_1.py
Interpreter¶
The package has been developed and tested with Python 2.6, 2.7, 3.3, 3.4 and 3.5 under Linux (Debian, Ubuntu), Apple OS X and Microsoft Windows
Installing¶
$ pip install pplot
Documentation¶
Available at Read the Docs
Contributing¶
Abide by the adopted code of conduct
Fork the repository from GitHub and then clone personal copy [1]:
$ git clone \ https://github.com/[github-user-name]/pplot.git Cloning into 'pplot'... ... $ cd pplot $ export PPLOT_DIR=${PWD}
Install the project’s Git hooks and build the documentation. The pre-commit hook does some minor consistency checks, namely trailing whitespace and PEP8 compliance via Pylint. Assuming the directory to which the repository was cloned is in the
$PPLOT_DIR
shell environment variable:$ ${PPLOT_DIR}/sbin/complete-cloning.sh Installing Git hooks Building pplot package documentation ...
Ensure that the Python interpreter can find the package modules (update the
$PYTHONPATH
environment variable, or use sys.paths(), etc.)$ export PYTHONPATH=${PYTHONPATH}:${PPLOT_DIR}
Install the dependencies (if needed, done automatically by pip):
- Astroid (Python 2.6: older than 1.4, Python 2.7 or newer: 1.3.8 or newer)
- Cog (2.4 or newer)
- Coverage (3.7.1 or newer)
- Decorator (3.4.2 or newer)
- Docutils (0.12 or newer)
- Funcsigs (Python 2.x only, 0.4 or newer)
- Inline Syntax Highlight Sphinx Extension (0.2 or newer)
- Matplotlib (1.4.1 or newer)
- Mock (Python 2.x only, 1.0.1 or newer)
- Nose (Python 2.6: 1.0.0 or newer)
- Numpy (1.8.2 or newer)
- Pcsv (1.0.0 or newer)
- Peng (1.0.0 or newer)
- Pexdoc (1.0.0 or newer)
- Pillow (2.6.1 or newer)
- Pmisc (1.0.0 or newer)
- Py.test (2.7.0 or newer)
- PyContracts (1.7.2 or newer except 1.7.7)
- PyParsing (2.0.7 or newer)
- Pylint (Python 2.6: 1.3 or newer and older than 1.4, Python 2.7 or newer: 1.3.1 or newer)
- Pytest-coverage (1.8.0 or newer)
- Pytest-xdist (optional, 1.8.0 or newer)
- ReadTheDocs Sphinx theme (0.1.9 or newer)
- Scipy (0.13.3 or newer)
- Six (1.4.0 or newer)
- Sphinx (1.2.3 or newer)
- Tox (1.9.0 or newer)
- Virtualenv (13.1.2 or newer)
Implement a new feature or fix a bug
Write a unit test which shows that the contributed code works as expected. Run the package tests to ensure that the bug fix or new feature does not have adverse side effects. If possible achieve 100% code and branch coverage of the contribution. Thorough package validation can be done via Tox and Py.test:
$ tox GLOB sdist-make: .../pplot/setup.py py26-pkg inst-nodeps: .../pplot/.tox/dist/pplot-...zip
Setuptools can also be used (Tox is configured as its virtual environment manager) [2]:
$ python setup.py tests running tests running egg_info writing requirements to pplot.egg-info/requires.txt writing pplot.egg-info/PKG-INFO ...
Tox (or Setuptools via Tox) runs with the following default environments:
py26-pkg
,py27-pkg
,py33-pkg
,py34-pkg
andpy35-pkg
[3]. These use the Python 2.6, 2.7, 3.3, 3.4 and 3.5 interpreters, respectively, to test all code in the documentation (both in Sphinx*.rst
source files and in docstrings), run all unit tests, measure test coverage and re-build the exceptions documentation. To pass arguments to Py.test (the test runner) use a double dash (--
) after all the Tox arguments, for example:$ tox -e py27-pkg -- -n 4 GLOB sdist-make: .../pplot/setup.py py27-pkg inst-nodeps: .../pplot/.tox/dist/pplot-...zip ...
Or use the
-a
Setuptools optional argument followed by a quoted string with the arguments for Py.test. For example:$ python setup.py tests -a "-e py27-pkg -- -n 4" running tests ...
There are other convenience environments defined for Tox [4]:
py26-repl
,py27-repl
,py33-repl
,py34-repl
andpy35-repl
run the Python 2.6, 2.7, 3.3, 3.4 or 3.5 REPL, respectively, in the appropriate virtual environment. Thepplot
package is pip-installed by Tox when the environments are created. Arguments to the interpreter can be passed in the command line after a double dash (--
)py26-test
,py27-test
,py33-test
,py34-test
andpy35-test
run py.test using the Python 2.6, 2.7, 3.3, 3.4 or Python 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
) , for example:$ tox -e py34-test -- -x test_pplot.py GLOB sdist-make: [...]/pplot/setup.py py34-test inst-nodeps: [...]/pplot/.tox/dist/pplot-[...].zip py34-test runtests: PYTHONHASHSEED='680528711' py34-test runtests: commands[0] | [...]py.test -x test_pplot.py ===================== test session starts ===================== platform linux -- Python 3.4.2 -- py-1.4.30 -- [...] ...
py26-cov
,py27-cov
,py33-cov
,py34-cov
andpy35-cov
test code and branch coverage using the Python 2.6, 2.7, 3.3, 3.4 or 3.5 interpreter, respectively, in the appropriate virtual environment. Arguments to py.test can be passed in the command line after a double dash (--
). The report can be found in${PPLOT_DIR}/.tox/py[PV]/usr/share/pplot/tests/htmlcov/index.html
where[PV]
stands for26
,27
,33
,34
or35
depending on the interpreter used
Verify that continuous integration tests pass. The package has continuous integration configured for Linux (via Travis) and for Microsoft Windows (via Appveyor). Aggregation/cloud code coverage is configured via Codecov. It is assumed that the Codecov repository upload token in the Travis build is stored in the
${CODECOV_TOKEN}
environment variable (securely defined in the Travis repository settings page). Travis build artifacts can be transferred to Dropbox using the Dropbox Uploader script (included for convenience in the${PPLOT_DIR}/sbin
directory). For an automatic transfer that does not require manual entering of authentication credentials place the APPKEY, APPSECRET, ACCESS_LEVEL, OAUTH_ACCESS_TOKEN and OAUTH_ACCESS_TOKEN_SECRET values required by Dropbox Uploader in the in the${DBU_APPKEY}
,${DBU_APPSECRET}
,${DBU_ACCESS_LEVEL}
,${DBU_OAUTH_ACCESS_TOKEN}
and${DBU_OAUTH_ACCESS_TOKEN_SECRET}
environment variables, respectively (also securely defined in Travis repository settings page)Document the new feature or bug fix (if needed). The script
${PPLOT_DIR}/sbin/build_docs.py
re-builds the whole package documentation (re-generates images, cogs source files, etc.):$ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] Build pplot package documentation optional arguments: -h, --help show this help message and exit -d DIRECTORY, --directory DIRECTORY specify source file directory (default ../pplot) -r, --rebuild rebuild exceptions documentation. If no module name is given all modules with auto-generated exceptions documentation are rebuilt -n NUM_CPUS, --num-cpus NUM_CPUS number of CPUs to use (default: 1) -t, --test diff original and rebuilt file(s) (exit code 0 indicates file(s) are identical, exit code 1 indicates file(s) are different)
Output of shell commands can be automatically included in reStructuredText source files with the help of Cog and the
docs.support.term_echo
module.-
docs.support.term_echo.
ste
(command, nindent, mdir, fpointer) Simplified terminal echo; prints STDOUT resulting from a given Bash shell command (relative to the package
sbin
directory) formatted in reStructuredTextParameters: - command (string) – Bash shell command, relative to
${PUTIL_DIR}/sbin
- nindent (integer) – Indentation level
- mdir (string) – Module directory
- fpointer (function object) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging
For example:
.. This is a reStructuredText file snippet .. [[[cog .. import os, sys .. from docs.support.term_echo import term_echo .. file_name = sys.modules['docs.support.term_echo'].__file__ .. mdir = os.path.realpath( .. os.path.dirname( .. os.path.dirname(os.path.dirname(file_name)) .. ) .. ) .. [[[cog ste('build_docs.py -h', 0, mdir, cog.out) ]]] .. code-block:: bash $ ${PUTIL_DIR}/sbin/build_docs.py -h usage: build_docs.py [-h] [-d DIRECTORY] [-r] [-n NUM_CPUS] [-t] [module_name [module_name ...]] ... .. ]]]
- command (string) – Bash shell command, relative to
-
docs.support.term_echo.
term_echo
(command, nindent=0, env=None, fpointer=None, cols=60) Terminal echo; prints STDOUT resulting from a given Bash shell command formatted in reStructuredText
Parameters: - command (string) – Bash shell command
- nindent (integer) – Indentation level
- env (dictionary) – Environment variable replacement dictionary. The Bash
command is pre-processed and any environment variable
represented in the full notation (
${...}
) is replaced. The dictionary key is the environment variable name and the dictionary value is the replacement value. For example, if command is'${PYTHON_CMD} -m "x=5"'
and env is{'PYTHON_CMD':'python3'}
the actual command issued is'python3 -m "x=5"'
- fpointer (function object) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging - cols (integer) – Number of columns of output
Similarly Python files can be included in docstrings with the help of Cog and the
docs.support.incfile
module-
docs.support.incfile.
incfile
(fname, fpointer, lrange='1, 6-', sdir=None) Includes a Python source file in a docstring formatted in reStructuredText
Parameters: - fname (string) – File name, relative to environment variable
${TRACER_DIR}
- fpointer (function object) – Output function pointer. Normally is
cog.out
butprint
or other functions can be used for debugging - lrange (string) – Line range to include, similar to Sphinx literalinclude directive
- sdir (string) – Source file directory. If None the
${TRACER_DIR}
environment variable is used if it is defined, otherwise the directory where thedocs.support.incfile
module is located is used
For example:
def func(): """ This is a docstring. This file shows how to use it: .. =[=cog .. import docs.support.incfile .. docs.support.incfile.incfile('func_example.py', cog.out) .. =]= .. code-block:: python # func_example.py if __name__ == '__main__': func() .. =[=end=]= """ return 'This is func output'
- fname (string) – File name, relative to environment variable
-
Footnotes
[1] | All examples are for the bash shell |
[2] | It appears that Scipy dependencies do not include Numpy (as they should) so running the tests via Setuptools will typically result in an error. The pplot requirement file specifies Numpy before Scipy and this installation order is honored by Tox so running the tests via Tox sidesteps Scipy’s broken dependency problem but requires Tox to be installed before running the tests (Setuptools installs Tox if needed) |
[3] | It is assumed that all the Python interpreters are in the executables path. Source code for the interpreters can be downloaded from Python’s main site |
[4] | Tox configuration largely inspired by Ionel’s codelog |
Changelog¶
- 1.0.0 [2016-05-12]: Final release of 1.0.0 branch
- 1.0.0rc1 [2016-05-12]: Initial commit, forked a subset from putil PyPI package
License¶
The MIT License (MIT)
Copyright (c) 2013-2016 Pablo Acosta-Serafini
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
API¶
Global variables¶
-
pplot.constants.
AXIS_LABEL_FONT_SIZE
= 18¶ Axis labels font size in points
Type: integer
-
pplot.constants.
LINE_WIDTH
= 2.5¶ Series line width in points
Type: float
-
pplot.constants.
LEGEND_SCALE
= 1.5¶ Scale factor for panel legend. The legend font size in points is equal to the axis font size divided by the legend scale
Type: number
-
pplot.constants.
MARKER_SIZE
= 14¶ Series marker size in points
Type: integer
-
pplot.constants.
MIN_TICKS
= 6¶ Minimum number of ticks desired for the independent and dependent axis of a panel
Type: integer
-
pplot.constants.
PRECISION
= 10¶ Number of mantissa significant digits used in all computations
Type: integer
-
pplot.constants.
SUGGESTED_MAX_TICKS
= 10¶ Maximum number of ticks desired for the independent and dependent axis of a panel. It is possible for a panel to have more than SUGGESTED_MAX_TICKS in the dependent axis if one or more series are plotted with an interpolation function and at least one interpolated curve goes above or below the maximum and minimum data points of the panel. In this case the panel will have SUGGESTED_MAX_TICKS+1 ticks if some interpolation curve is above the maximum data point of the panel or below the minimum data point of the panel; or the panel will have SUGGESTED_MAX_TICKS+2 ticks if some interpolation curve(s) is(are) above the maximum data point of the panel and below the minimum data point of the panel
Type: integer
-
pplot.constants.
TITLE_FONT_SIZE
= 24¶ Figure title font size in points
Type: integer
Functions¶
-
pplot.
parameterized_color_space
(param_list, offset=0, color_space='binary')¶ Computes a color space where lighter colors correspond to lower parameter values
Parameters: - param_list (list) – Parameter values
- offset (OffsetRange) – Offset of the first (lightest) color
- color_space (ColorSpaceOption) – Color palette (case sensitive)
Return type: Raises: - RuntimeError (Argument `color_space` is not valid)
- RuntimeError (Argument `offset` is not valid)
- RuntimeError (Argument `param_list` is not valid)
- TypeError (Argument `param_list` is empty)
- ValueError (Argument `color_space` is not one of ‘binary’, ‘Blues’, ‘BuGn’, ‘BuPu’, ‘GnBu’, ‘Greens’, ‘Greys’, ‘Oranges’, ‘OrRd’, ‘PuBu’, ‘PuBuGn’, ‘PuRd’, ‘Purples’, ‘RdPu’, ‘Reds’, ‘YlGn’, ‘YlGnBu’, ‘YlOrBr’ or ‘YlOrRd’ (case insensitive))
Classes¶
- class
pplot.functions.
DataSource
¶Bases: object
Abstract base class for data sources. The following example is a minimal implementation of a data source class:
# plot_example_2.py import pplot class MySource(pplot.DataSource, object): def __init__(self): super(MySource, self).__init__() def __str__(self): return super(MySource, self).__str__() def _set_dep_var(self, dep_var): super(MySource, self)._set_dep_var(dep_var) def _set_indep_var(self, indep_var): super(MySource, self)._set_indep_var(indep_var) dep_var = property( pplot.DataSource._get_dep_var, _set_dep_var ) indep_var = property( pplot.DataSource._get_indep_var, _set_indep_var )Warning
The abstract methods listed below need to be defined in a child class
__str__
()¶Pretty prints the stored independent and dependent variables. For example:
>>> from __future__ import print_function >>> import numpy, docs.support.plot_example_2 >>> obj = docs.support.plot_example_2.MySource() >>> obj.indep_var = numpy.array([1, 2, 3]) >>> obj.dep_var = numpy.array([-1, 1, -1]) >>> print(obj) Independent variable: [ 1.0, 2.0, 3.0 ] Dependent variable: [ -1.0, 1.0, -1.0 ]
_set_dep_var
(dep_var)¶Sets the dependent variable (casting to float type). For example:
>>> import numpy, docs.support.plot_example_2 >>> obj = docs.support.plot_example_2.MySource() >>> obj.dep_var = numpy.array([-1, 1, -1]) >>> obj.dep_var array([-1., 1., -1.])
_set_indep_var
(indep_var)¶Sets the independent variable (casting to float type). For example:
>>> import numpy, docs.support.plot_example_2 >>> obj = docs.support.plot_example_2.MySource() >>> obj.indep_var = numpy.array([1, 2, 3]) >>> obj.indep_var array([ 1., 2., 3.])
- class
pplot.
BasicSource
(indep_var, dep_var, indep_min=None, indep_max=None)¶Bases: pplot.functions.DataSource
Objects of this class hold a given data set intended for plotting. It is a convenient way to plot manually-entered data or data coming from a source that does not export to a comma-separated values (CSV) file.
Parameters:
- indep_var (IncreasingRealNumpyVector) – Independent variable vector
- dep_var (RealNumpyVector) – Dependent variable vector
- indep_min (RealNum or None) – Minimum independent variable value. If None no minimum thresholding is applied to the data
- indep_max – Maximum independent variable value. If None no maximum thresholding is applied to the data
Return type:
Raises:
- RuntimeError (Argument `dep_var` is not valid)
- RuntimeError (Argument `indep_max` is not valid)
- RuntimeError (Argument `indep_min` is not valid)
- RuntimeError (Argument `indep_var` is not valid)
- ValueError (Argument `indep_min` is greater than argument `indep_max`)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
__str__
()¶Prints source information. For example:
# plot_example_4.py import numpy, pplot def create_basic_source(): obj = pplot.BasicSource( indep_var=numpy.array([1, 2, 3, 4]), dep_var=numpy.array([1, -10, 10, 5]), indep_min=2, indep_max=3 ) return obj>>> from __future__ import print_function >>> import docs.support.plot_example_4 >>> obj = docs.support.plot_example_4.create_basic_source() >>> print(obj) Independent variable minimum: 2 Independent variable maximum: 3 Independent variable: [ 2.0, 3.0 ] Dependent variable: [ -10.0, 10.0 ]
dep_var
¶Gets or sets the dependent variable data
Type: RealNumpyVector
Raises: (when assigned)
- RuntimeError (Argument `dep_var` is not valid)
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
indep_max
¶Gets or sets the maximum independent variable limit. If
None
no maximum thresholding is applied to the data
Type: RealNum or None
Raises: (when assigned)
- RuntimeError (Argument `indep_max` is not valid)
- ValueError (Argument `indep_min` is greater than argument `indep_max`)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
indep_min
¶Gets or sets the minimum independent variable limit. If
None
no minimum thresholding is applied to the data
Type: RealNum or None
Raises: (when assigned)
- RuntimeError (Argument `indep_min` is not valid)
- ValueError (Argument `indep_min` is greater than argument `indep_max`)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
indep_var
¶Gets or sets the independent variable data
Type: IncreasingRealNumpyVector
Raises: (when assigned)
- RuntimeError (Argument `indep_var` is not valid)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
- class
pplot.
CsvSource
(fname, indep_col_label, dep_col_label, rfilter=None, indep_min=None, indep_max=None, fproc=None, fproc_eargs=None)¶Bases: pplot.functions.DataSource
Objects of this class hold a data set from a CSV file intended for plotting. The raw data from the file can be filtered and a callback function can be used for more general data pre-processing
Parameters:
- fname (FileNameExists) – Comma-separated values file name
- indep_col_label (string) – Independent variable column label (case insensitive)
- dep_col_label (string) – Dependent variable column label (case insensitive)
- rfilter (CsvRowFilter or None) – Row filter specification. If None no row filtering is performed
- indep_min – Minimum independent variable value. If None no minimum thresholding is applied to the data
- indep_max – Maximum independent variable value. If None no maximum thresholding is applied to the data
- fproc (Function or None) – Data processing function. If None no processing function is used
- fproc_eargs (dictionary or None) – Data processing function extra arguments. If None no extra arguments are passed to the processing function (if defined)
Return type: Note
The row where data starts in the comma-separated file is auto-detected as the first row that has a number (integer or float) in at least one of its columns
Raises:
- OSError (File [fname] could not be found)
- RuntimeError (Argument `dep_col_label` is not valid)
- RuntimeError (Argument `dep_var` is not valid)
- RuntimeError (Argument `fname` is not valid)
- RuntimeError (Argument `fproc_eargs` is not valid)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Argument `fproc` is not valid)
- RuntimeError (Argument `indep_col_label` is not valid)
- RuntimeError (Argument `indep_max` is not valid)
- RuntimeError (Argument `indep_min` is not valid)
- RuntimeError (Argument `indep_var` is not valid)
- RuntimeError (Argument `rfilter` is not valid)
- RuntimeError (Column headers are not unique in file [fname])
- RuntimeError (File [fname] has no valid data)
- RuntimeError (File [fname] is empty)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Argument `fproc` (function [func_name]) does not have at least 2 arguments)
- ValueError (Argument `indep_min` is greater than argument `indep_max`)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
- ValueError (Argument `rfilter` is empty)
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
- ValueError (Column [col_name] (dependent column label) could not be found in comma-separated file [fname] header)
- ValueError (Column [col_name] (independent column label) could not be found in comma-separated file [fname] header)
- ValueError (Column [col_name] in row filter not found in comma- separated file [fname] header)
- ValueError (Column [column_identifier] not found)
- ValueError (Extra argument `*[arg_name]*` not found in argument `fproc` (function [func_name]) definition)
- ValueError (Filtered dependent variable is empty)
- ValueError (Filtered independent variable is empty)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
__str__
()¶Prints source information. For example:
# plot_example_3.py import pmisc, pcsv def cwrite(fobj, data): fobj.write(data) def write_csv_file(file_handle): cwrite(file_handle, 'Col1,Col2\n') cwrite(file_handle, '0E-12,10\n') cwrite(file_handle, '1E-12,0\n') cwrite(file_handle, '2E-12,20\n') cwrite(file_handle, '3E-12,-10\n') cwrite(file_handle, '4E-12,30\n') # indep_var is a Numpy vector, in this example time, # in seconds. dep_var is a Numpy vector def proc_func1(indep_var, dep_var): # Scale time to pico-seconds indep_var = indep_var/1e-12 # Remove offset dep_var = dep_var-dep_var[0] return indep_var, dep_var def create_csv_source(): with pmisc.TmpFile(write_csv_file) as fname: obj = pplot.CsvSource( fname=fname, indep_col_label='Col1', dep_col_label='Col2', indep_min=2E-12, fproc=proc_func1 ) return obj>>> from __future__ import print_function >>> import docs.support.plot_example_3 >>> obj = docs.support.plot_example_3.create_csv_source() >>> print(obj) File name: ... Row filter: None Independent column label: Col1 Dependent column label: Col2 Processing function: proc_func1 Processing function extra arguments: None Independent variable minimum: 2e-12 Independent variable maximum: +inf Independent variable: [ 2.0, 3.0, 4.0 ] Dependent variable: [ 0.0, -30.0, 10.0 ]
dep_col_label
¶Gets or sets the dependent variable column label (column name)
Type: string
Raises: (when assigned)
- RuntimeError (Argument `dep_col_label` is not valid)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Column [col_name] (dependent column label) could not be found in comma-separated file [fname] header)
- ValueError (Column [col_name] in row filter not found in comma- separated file [fname] header)
- ValueError (Filtered dependent variable is empty)
- ValueError (Filtered independent variable is empty)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
dep_var
¶Gets the dependent variable Numpy vector
fname
¶Gets or sets the comma-separated values file from which data series is to be extracted. It is assumed that the first line of the file contains unique headers for each column
Type: string
Raises: (when assigned)
- OSError (File [fname] could not be found)
- RuntimeError (Argument `dep_var` is not valid)
- RuntimeError (Argument `fname` is not valid)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Argument `indep_var` is not valid)
- RuntimeError (Argument `rfilter` is not valid)
- RuntimeError (Column headers are not unique in file [fname])
- RuntimeError (File [fname] has no valid data)
- RuntimeError (File [fname] is empty)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
- ValueError (Argument `rfilter` is empty)
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
- ValueError (Column [col_name] (dependent column label) could not be found in comma-separated file [fname] header)
- ValueError (Column [col_name] (independent column label) could not be found in comma-separated file [fname] header)
- ValueError (Column [col_name] in row filter not found in comma- separated file [fname] header)
- ValueError (Column [column_identifier] not found)
- ValueError (Filtered dependent variable is empty)
- ValueError (Filtered independent variable is empty)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
fproc
¶Gets or sets the data processing function pointer. The processing function is useful for “light” data massaging, like scaling, unit conversion, etc.; it is called after the data has been retrieved from the comma-separated values file and the resulting filtered data set has been bounded (if applicable). If
None
no processing function is used.When defined the processing function is given two arguments, a Numpy vector containing the independent variable array (first argument) and a Numpy vector containing the dependent variable array (second argument). The expected return value is a two-item Numpy vector tuple, its first item being the processed independent variable array, and the second item being the processed dependent variable array. One valid processing function could be:
# indep_var is a Numpy vector, in this example time, # in seconds. dep_var is a Numpy vector def proc_func1(indep_var, dep_var): # Scale time to pico-seconds indep_var = indep_var/1e-12 # Remove offset dep_var = dep_var-dep_var[0] return indep_var, dep_var
Type: Function or None
Raises: (when assigned)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Argument `fproc` is not valid)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Argument `fproc` (function [func_name]) does not have at least 2 arguments)
- ValueError (Extra argument `*[arg_name]*` not found in argument `fproc` (function [func_name]) definition)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
fproc_eargs
¶Gets or sets the extra arguments for the data processing function. The arguments are specified by key-value pairs of a dictionary, for each dictionary element the dictionary key specifies the argument name and the dictionary value specifies the argument value. The extra parameters are passed by keyword so they must appear in the function definition explicitly or keyword variable argument collection must be used (
**kwargs
, for example). IfNone
no extra arguments are passed to the processing function (if defined)
Type: dictionary or None
Raises: (when assigned)
- RuntimeError (Argument `fproc_eargs` is not valid)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Extra argument `*[arg_name]*` not found in argument `fproc` (function [func_name]) definition)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
For example:
# plot_example_5.py import sys, pmisc, pcsv if sys.hexversion < 0x03000000: from pplot.compat2 import _write else: from pplot.compat3 import _write def write_csv_file(file_handle): _write(file_handle, 'Col1,Col2\n') _write(file_handle, '0E-12,10\n') _write(file_handle, '1E-12,0\n') _write(file_handle, '2E-12,20\n') _write(file_handle, '3E-12,-10\n') _write(file_handle, '4E-12,30\n') def proc_func2(indep_var, dep_var, par1, par2): return (indep_var/1E-12)+(2*par1), dep_var+sum(par2) def create_csv_source(): with pmisc.TmpFile(write_csv_file) as fname: obj = pplot.CsvSource( fname=fname, indep_col_label='Col1', dep_col_label='Col2', fproc=proc_func2, fproc_eargs={'par1':5, 'par2':[1, 2, 3]} ) return obj>>> from __future__ import print_function >>> import docs.support.plot_example_5 >>> obj = docs.support.plot_example_5.create_csv_source() >>> print(obj) File name: ... Row filter: None Independent column label: Col1 Dependent column label: Col2 Processing function: proc_func2 Processing function extra arguments: None Independent variable minimum: -inf Independent variable maximum: +inf Independent variable: [ 10, 11, 12, 13, 14 ] Dependent variable: [ 16, 6, 26, -4, 36 ]
indep_col_label
¶Gets or sets the independent variable column label (column name)
Type: string
Raises: (when assigned)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Argument `indep_col_label` is not valid)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Column [col_name] (independent column label) could not be found in comma-separated file [fname] header)
- ValueError (Column [col_name] in row filter not found in comma- separated file [fname] header)
- ValueError (Filtered dependent variable is empty)
- ValueError (Filtered independent variable is empty)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
indep_max
¶Gets or sets the maximum independent variable limit. If
None
no maximum thresholding is applied to the data
Type: RealNum or None
Raises: (when assigned)
- RuntimeError (Argument `indep_max` is not valid)
- ValueError (Argument `indep_min` is greater than argument `indep_max`)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
indep_min
¶Gets or sets the minimum independent variable limit. If
None
no minimum thresholding is applied to the data
Type: RealNum or None
Raises: (when assigned)
- RuntimeError (Argument `indep_min` is not valid)
- ValueError (Argument `indep_min` is greater than argument `indep_max`)
- ValueError (Argument `indep_var` is empty after `indep_min`/`indep_max` range bounding)
indep_var
¶Gets the independent variable Numpy vector
rfilter
¶Gets or sets the row filter. If
None
no row filtering is performed
Type: CsvRowFilter or None
Raises: (when assigned)
- RuntimeError (Argument `fproc` (function [func_name]) returned an illegal number of values)
- RuntimeError (Argument `rfilter` is not valid)
- RuntimeError (Processing function [func_name] raised an exception when called with the following arguments:
\n
indep_var: [indep_var_value]\n
dep_var: [dep_var_value]\n
fproc_eargs: [fproc_eargs_value]\n
Exception error: [exception_error_message])- TypeError (Argument `fproc` (function [func_name]) return value is not valid)
- TypeError (Processed dependent variable is not valid)
- TypeError (Processed independent variable is not valid)
- ValueError (Argument `rfilter` is empty)
- ValueError (Column [col_name] in row filter not found in comma- separated file [fname] header)
- ValueError (Filtered dependent variable is empty)
- ValueError (Filtered independent variable is empty)
- ValueError (Processed dependent variable is empty)
- ValueError (Processed independent and dependent variables are of different length)
- ValueError (Processed independent variable is empty)
- class
pplot.
Series
(data_source, label, color='k', marker='o', interp='CUBIC', line_style='-', secondary_axis=False)¶Bases: object
Specifies a series within a panel
Parameters:
- data_source (pplot.BasicSource, pplot.CsvSource or others conforming to the data source specification) – Data source object
- label (string) – Series label, to be used in the panel legend
- color (polymorphic) – Series color. All Matplotlib colors are supported
- marker (string or None) – Marker type. All Matplotlib marker types are supported. None indicates no marker
- interp (InterpolationOption or None) – Interpolation option (case insensitive), one of None (no interpolation) ‘STRAIGHT’ (straight line connects data points), ‘STEP’ (horizontal segments between data points), ‘CUBIC’ (cubic interpolation between data points) or ‘LINREG’ (linear regression based on data points). The interpolation option is case insensitive
- line_style (LineStyleOption or None) – Line style. All Matplotlib line styles are supported. None indicates no line
- secondary_axis (boolean) – Flag that indicates whether the series belongs to the panel primary axis (False) or secondary axis (True)
Raises:
- RuntimeError (Argument `color` is not valid)
- RuntimeError (Argument `data_source` does not have an `dep_var` attribute)
- RuntimeError (Argument `data_source` does not have an `indep_var` attribute)
- RuntimeError (Argument `data_source` is not fully specified)
- RuntimeError (Argument `interp` is not valid)
- RuntimeError (Argument `label` is not valid)
- RuntimeError (Argument `line_style` is not valid)
- RuntimeError (Argument `marker` is not valid)
- RuntimeError (Argument `secondary_axis` is not valid)
- TypeError (Invalid color specification)
- ValueError (Argument `interp` is not one of [‘STRAIGHT’, ‘STEP’, ‘CUBIC’, ‘LINREG’] (case insensitive))
- ValueError (Argument `line_style` is not one of [‘-‘, ‘–’, ‘-.’, ‘:’])
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
- ValueError (At least 4 data points are needed for CUBIC interpolation)
__str__
()¶Print series object information
color
¶Gets or sets the series line and marker color. All Matplotlib colors are supported
Type: polymorphic
Raises: (when assigned)
- RuntimeError (Argument `color` is not valid)
- TypeError (Invalid color specification)
data_source
¶Gets or sets the data source object. The independent and dependent data sets are obtained once this attribute is set. To be valid, a data source object must have an
indep_var
attribute that contains a Numpy vector of increasing real numbers and adep_var
attribute that contains a Numpy vector of real numbers
Type: pplot.BasicSource, pplot.CsvSource or others conforming to the data source specification
Raises: (when assigned)
- RuntimeError (Argument `data_source` does not have an `dep_var` attribute)
- RuntimeError (Argument `data_source` does not have an `indep_var` attribute)
- RuntimeError (Argument `data_source` is not fully specified)
- ValueError (Arguments `indep_var` and `dep_var` must have the same number of elements)
- ValueError (At least 4 data points are needed for CUBIC interpolation)
interp
¶Gets or sets the interpolation option, one of
None
(no interpolation)'STRAIGHT'
(straight line connects data points),'STEP'
(horizontal segments between data points),'CUBIC'
(cubic interpolation between data points) or'LINREG'
(linear regression based on data points). The interpolation option is case insensitive
Type: InterpolationOption or None
Raises: (when assigned)
- RuntimeError (Argument `interp` is not valid)
- ValueError (Argument `interp` is not one of [‘STRAIGHT’, ‘STEP’, ‘CUBIC’, ‘LINREG’] (case insensitive))
- ValueError (At least 4 data points are needed for CUBIC interpolation)
label
¶Gets or sets the series label, to be used in the panel legend if the panel has more than one series
Type: string
Raises: (when assigned) RuntimeError (Argument `label` is not valid)
line_style
¶Sets or gets the line style. All Matplotlib line styles are supported.
None
indicates no line
Type: LineStyleOption
Raises: (when assigned)
- RuntimeError (Argument `line_style` is not valid)
- ValueError (Argument `line_style` is not one of [‘-‘, ‘–’, ‘-.’, ‘:’])
marker
¶Gets or sets the series marker type. All Matplotlib marker types are supported.
None
indicates no marker
Type: string or None
Raises: (when assigned) RuntimeError (Argument `marker` is not valid)
secondary_axis
¶Sets or gets the secondary axis flag; indicates whether the series belongs to the panel primary axis (False) or secondary axis (True)
Type: boolean
Raises: (when assigned) RuntimeError (Argument `secondary_axis` is not valid)
- class
pplot.
Panel
(series=None, primary_axis_label='', primary_axis_units='', primary_axis_ticks=None, secondary_axis_label='', secondary_axis_units='', secondary_axis_ticks=None, log_dep_axis=False, legend_props=None, display_indep_axis=False)¶Bases: object
Defines a panel within a figure
Parameters:
- series (pplot.Series or list of pplot.Series or None) – One or more data series
- primary_axis_label (string) – Primary dependent axis label
- primary_axis_units (string) – Primary dependent axis units
- primary_axis_ticks (list, Numpy vector or None) – Primary dependent axis tick marks. If not None overrides automatically generated tick marks if the axis type is linear. If None automatically generated tick marks are used for the primary axis
- secondary_axis_label (string) – Secondary dependent axis label
- secondary_axis_units (string) – Secondary dependent axis units
- secondary_axis_ticks (list, Numpy vector or None) – Secondary dependent axis tick marks. If not None overrides automatically generated tick marks if the axis type is linear. If None automatically generated tick marks are used for the secondary axis
- log_dep_axis (boolean) – Flag that indicates whether the dependent (primary and /or secondary) axis is linear (False) or logarithmic (True)
- legend_props (dictionary or None) – Legend properties. See pplot.Panel.legend_props. If None the legend is placed in the best position in one column
- display_indep_axis (boolean) – Flag that indicates whether the independent axis is displayed (True) or not (False)
Raises:
- RuntimeError (Argument `display_indep_axis` is not valid)
- RuntimeError (Argument `legend_props` is not valid)
- RuntimeError (Argument `log_dep_axis` is not valid)
- RuntimeError (Argument `primary_axis_label` is not valid)
- RuntimeError (Argument `primary_axis_ticks` is not valid)
- RuntimeError (Argument `primary_axis_units` is not valid)
- RuntimeError (Argument `secondary_axis_label` is not valid)
- RuntimeError (Argument `secondary_axis_ticks` is not valid)
- RuntimeError (Argument `secondary_axis_units` is not valid)
- RuntimeError (Argument `series` is not valid)
- RuntimeError (Legend property `cols` is not valid)
- RuntimeError (Series item [number] is not fully specified)
- TypeError (Legend property `pos` is not one of [‘BEST’, ‘UPPER RIGHT’, ‘UPPER LEFT’, ‘LOWER LEFT’, ‘LOWER RIGHT’, ‘RIGHT’, ‘CENTER LEFT’, ‘CENTER RIGHT’, ‘LOWER CENTER’, ‘UPPER CENTER’, ‘CENTER’] (case insensitive))
- ValueError (Illegal legend property `*[prop_name]*`)
- ValueError (Series item [number] cannot be plotted in a logarithmic axis because it contains negative data points)
__bool__
()¶Returns
True
if the panel has at least a series associated with it,False
otherwiseNote
This method applies to Python 3.x
__iter__
()¶Returns an iterator over the series object(s) in the panel. For example:
# plot_example_6.py from __future__ import print_function import numpy, pplot def panel_iterator_example(no_print): source1 = pplot.BasicSource( indep_var=numpy.array([1, 2, 3, 4]), dep_var=numpy.array([1, -10, 10, 5]) ) source2 = pplot.BasicSource( indep_var=numpy.array([100, 200, 300, 400]), dep_var=numpy.array([50, 75, 100, 125]) ) series1 = pplot.Series( data_source=source1, label='Goals' ) series2 = pplot.Series( data_source=source2, label='Saves', color='b', marker=None, interp='STRAIGHT', line_style='--' ) panel = pplot.Panel( series=[series1, series2], primary_axis_label='Time', primary_axis_units='sec', display_indep_axis=True ) if not no_print: for num, series in enumerate(panel): print('Series {0}:'.format(num+1)) print(series) print('') else: return panel>>> import docs.support.plot_example_6 as mod >>> mod.panel_iterator_example(False) Series 1: Independent variable: [ 1.0, 2.0, 3.0, 4.0 ] Dependent variable: [ 1.0, -10.0, 10.0, 5.0 ] Label: Goals Color: k Marker: o Interpolation: CUBIC Line style: - Secondary axis: False Series 2: Independent variable: [ 100.0, 200.0, 300.0, 400.0 ] Dependent variable: [ 50.0, 75.0, 100.0, 125.0 ] Label: Saves Color: b Marker: None Interpolation: STRAIGHT Line style: -- Secondary axis: False
__nonzero__
()¶Returns
True
if the panel has at least a series associated with it,False
otherwiseNote
This method applies to Python 2.x
__str__
()¶Prints panel information. For example:
>>> from __future__ import print_function >>> import docs.support.plot_example_6 as mod >>> print(mod.panel_iterator_example(True)) Series 0: Independent variable: [ 1.0, 2.0, 3.0, 4.0 ] Dependent variable: [ 1.0, -10.0, 10.0, 5.0 ] Label: Goals Color: k Marker: o Interpolation: CUBIC Line style: - Secondary axis: False Series 1: Independent variable: [ 100.0, 200.0, 300.0, 400.0 ] Dependent variable: [ 50.0, 75.0, 100.0, 125.0 ] Label: Saves Color: b Marker: None Interpolation: STRAIGHT Line style: -- Secondary axis: False Primary axis label: Time Primary axis units: sec Secondary axis label: not specified Secondary axis units: not specified Logarithmic dependent axis: False Display independent axis: True Legend properties: cols: 1 pos: BEST
display_indep_axis
¶Gets or sets the independent axis display flag; indicates whether the independent axis is displayed (True) or not (False)
Type: boolean
Raises: (when assigned) RuntimeError (Argument `display_indep_axis` is not valid)
legend_props
¶Gets or sets the panel legend box properties; this is a dictionary that has properties (dictionary key) and their associated values (dictionary values). Currently supported properties are:
- pos (string) – legend box position, one of
'BEST'
,'UPPER RIGHT'
,'UPPER LEFT'
,'LOWER LEFT'
,'LOWER RIGHT'
,'RIGHT'
,'CENTER LEFT'
,'CENTER RIGHT'
,'LOWER CENTER'
,'UPPER CENTER'
or'CENTER'
(case insensitive)- cols (integer) – number of columns of the legend box
If
None
the default used is{'pos':'BEST', 'cols':1}
Note
No legend is shown if a panel has only one series in it or if no series has a label
Type: dictionary
Raises: (when assigned)
- RuntimeError (Argument `legend_props` is not valid)
- RuntimeError (Legend property `cols` is not valid)
- TypeError (Legend property `pos` is not one of [‘BEST’, ‘UPPER RIGHT’, ‘UPPER LEFT’, ‘LOWER LEFT’, ‘LOWER RIGHT’, ‘RIGHT’, ‘CENTER LEFT’, ‘CENTER RIGHT’, ‘LOWER CENTER’, ‘UPPER CENTER’, ‘CENTER’] (case insensitive))
- ValueError (Illegal legend property `*[prop_name]*`)
log_dep_axis
¶Gets or sets the panel logarithmic dependent (primary and/or secondary) axis flag; indicates whether the dependent (primary and/or secondary) axis is linear (False) or logarithmic (True)
Type: boolean
Raises: (when assigned)
- RuntimeError (Argument `log_dep_axis` is not valid)
- RuntimeError (Argument `series` is not valid)
- RuntimeError (Series item [number] is not fully specified)
- ValueError (Series item [number] cannot be plotted in a logarithmic axis because it contains negative data points)
primary_axis_label
¶Gets or sets the panel primary dependent axis label
Type: string
Raises: (when assigned) RuntimeError (Argument `primary_axis_label` is not valid)
primary_axis_scale
¶Gets the scale of the panel primary axis,
None
if axis has no series associated with it
Type: float or None
primary_axis_ticks
¶Gets the primary axis (scaled) tick locations,
None
if axis has no series associated with it
Type: list or None
primary_axis_units
¶Gets or sets the panel primary dependent axis units
Type: string
Raises: (when assigned) RuntimeError (Argument `primary_axis_units` is not valid)
secondary_axis_label
¶Gets or sets the panel secondary dependent axis label
Type: string
Raises: (when assigned) RuntimeError (Argument `secondary_axis_label` is not valid)
secondary_axis_scale
¶Gets the scale of the panel secondary axis,
None
if axis has no series associated with it
Type: float or None
secondary_axis_ticks
¶Gets the secondary axis (scaled) tick locations,
None
if axis has no series associated with it
Type: list or None with it
secondary_axis_units
¶Gets or sets the panel secondary dependent axis units
Type: string
Raises: (when assigned) RuntimeError (Argument `secondary_axis_units` is not valid)
series
¶Gets or sets the panel series,
None
if there are no series associated with the panel
Type: pplot.Series, list of pplot.Series or None
Raises: (when assigned)
- RuntimeError (Argument `series` is not valid)
- RuntimeError (Series item [number] is not fully specified)
- ValueError (Series item [number] cannot be plotted in a logarithmic axis because it contains negative data points)
- class
pplot.
Figure
(panels=None, indep_var_label='', indep_var_units='', indep_axis_ticks=None, fig_width=None, fig_height=None, title='', log_indep_axis=False)¶Bases: object
Generates presentation-quality plots
Parameters:
- panels (pplot.Panel or list of pplot.Panel or None) – One or more data panels
- indep_var_label (string) – Independent variable label
- indep_var_units (string) – Independent variable units
- indep_axis_ticks (list, Numpy vector or None) – Independent axis tick marks. If not None overrides automatically generated tick marks if the axis type is linear. If None automatically generated tick marks are used for the independent axis
- fig_width (PositiveRealNum or None) – Hard copy plot width in inches. If None the width is automatically calculated so that there is no horizontal overlap between any two text elements in the figure
- fig_height – Hard copy plot height in inches. If None the height is automatically calculated so that there is no vertical overlap between any two text elements in the figure
- title (string) – Plot title
- log_indep_axis (boolean) – Flag that indicates whether the independent axis is linear (False) or logarithmic (True)
Raises:
- RuntimeError (Argument `fig_height` is not valid)
- RuntimeError (Argument `fig_width` is not valid)
- RuntimeError (Argument `indep_axis_ticks` is not valid)
- RuntimeError (Argument `indep_var_label` is not valid)
- RuntimeError (Argument `indep_var_units` is not valid)
- RuntimeError (Argument `log_indep_axis` is not valid)
- RuntimeError (Argument `panels` is not valid)
- RuntimeError (Argument `title` is not valid)
- RuntimeError (Figure object is not fully specified)
- RuntimeError (Figure size is too small: minimum width [min_width], minimum height [min_height])
- TypeError (Panel [panel_num] is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
__bool__
()¶Returns
True
if the figure has at least a panel associated with it,False
otherwiseNote
This method applies to Python 3.x
__iter__
()¶Returns an iterator over the panel object(s) in the figure. For example:
# plot_example_7.py from __future__ import print_function import numpy, pplot def figure_iterator_example(no_print): source1 = pplot.BasicSource( indep_var=numpy.array([1, 2, 3, 4]), dep_var=numpy.array([1, -10, 10, 5]) ) source2 = pplot.BasicSource( indep_var=numpy.array([100, 200, 300, 400]), dep_var=numpy.array([50, 75, 100, 125]) ) series1 = pplot.Series( data_source=source1, label='Goals' ) series2 = pplot.Series( data_source=source2, label='Saves', color='b', marker=None, interp='STRAIGHT', line_style='--' ) panel1 = pplot.Panel( series=series1, primary_axis_label='Average', primary_axis_units='A', display_indep_axis=False ) panel2 = pplot.Panel( series=series2, primary_axis_label='Standard deviation', primary_axis_units=r'$\sqrt{{A}}$', display_indep_axis=True ) figure = pplot.Figure( panels=[panel1, panel2], indep_var_label='Time', indep_var_units='sec', title='Sample Figure' ) if not no_print: for num, panel in enumerate(figure): print('Panel {0}:'.format(num+1)) print(panel) print('') else: return figure>>> import docs.support.plot_example_7 as mod >>> mod.figure_iterator_example(False) Panel 1: Series 0: Independent variable: [ 1.0, 2.0, 3.0, 4.0 ] Dependent variable: [ 1.0, -10.0, 10.0, 5.0 ] Label: Goals Color: k Marker: o Interpolation: CUBIC Line style: - Secondary axis: False Primary axis label: Average Primary axis units: A Secondary axis label: not specified Secondary axis units: not specified Logarithmic dependent axis: False Display independent axis: False Legend properties: cols: 1 pos: BEST Panel 2: Series 0: Independent variable: [ 100.0, 200.0, 300.0, 400.0 ] Dependent variable: [ 50.0, 75.0, 100.0, 125.0 ] Label: Saves Color: b Marker: None Interpolation: STRAIGHT Line style: -- Secondary axis: False Primary axis label: Standard deviation Primary axis units: $\sqrt{{A}}$ Secondary axis label: not specified Secondary axis units: not specified Logarithmic dependent axis: False Display independent axis: True Legend properties: cols: 1 pos: BEST
__nonzero__
()¶Returns
True
if the figure has at least a panel associated with it,False
otherwiseNote
This method applies to Python 2.x
__str__
()¶Prints figure information. For example:
>>> from __future__ import print_function >>> import docs.support.plot_example_7 as mod >>> print(mod.figure_iterator_example(True)) Panel 0: Series 0: Independent variable: [ 1.0, 2.0, 3.0, 4.0 ] Dependent variable: [ 1.0, -10.0, 10.0, 5.0 ] Label: Goals Color: k Marker: o Interpolation: CUBIC Line style: - Secondary axis: False Primary axis label: Average Primary axis units: A Secondary axis label: not specified Secondary axis units: not specified Logarithmic dependent axis: False Display independent axis: False Legend properties: cols: 1 pos: BEST Panel 1: Series 0: Independent variable: [ 100.0, 200.0, 300.0, 400.0 ] Dependent variable: [ 50.0, 75.0, 100.0, 125.0 ] Label: Saves Color: b Marker: None Interpolation: STRAIGHT Line style: -- Secondary axis: False Primary axis label: Standard deviation Primary axis units: $\sqrt{{A}}$ Secondary axis label: not specified Secondary axis units: not specified Logarithmic dependent axis: False Display independent axis: True Legend properties: cols: 1 pos: BEST Independent variable label: Time Independent variable units: sec Logarithmic independent axis: False Title: Sample Figure Figure width: ... Figure height: ...
save
(fname, ftype='PNG')¶Saves the figure to a file
Parameters:
Raises:
- RuntimeError (Argument `fname` is not valid)
- RuntimeError (Argument `ftype` is not valid)
- RuntimeError (Figure object is not fully specified)
- RuntimeError (Unsupported file type: [file_type])
show
()¶Displays the figure
Raises:
- RuntimeError (Figure object is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
axes_list
¶Gets the Matplotlib figure axes handle list or
None
if figure is not fully specified. Useful if annotations or further customizations to the panel(s) are needed. Each panel has an entry in the list, which is sorted in the order the panels are plotted (top to bottom). Each panel entry is a dictionary containing the following key-value pairs:
- number (integer) – panel number, panel 0 is the top-most panel
- primary (Matplotlib axis object) – axis handle for the primary axis, None if the figure has not primary axis
- secondary (Matplotlib axis object) – axis handle for the secondary axis, None if the figure has no secondary axis
Type: list
fig
¶Gets the Matplotlib figure handle. Useful if annotations or further customizations to the figure are needed.
None
if figure is not fully specified
Type: Matplotlib figure handle or None
fig_height
¶Gets or sets the height (in inches) of the hard copy plot,
None
if figure is not fully specified.
Type: PositiveRealNum or None
Raises: (when assigned) RuntimeError (Argument `fig_height` is not valid)
fig_width
¶Gets or sets the width (in inches) of the hard copy plot,
None
if figure is not fully specified
Type: PositiveRealNum or None
Raises: (when assigned) RuntimeError (Argument `fig_width` is not valid)
indep_axis_scale
¶Gets the scale of the figure independent axis,
None
if figure is not fully specified
Type: float or None if figure has no panels associated with it
indep_axis_ticks
¶Gets the independent axis (scaled) tick locations,
None
if figure is not fully specified
Type: list
indep_var_label
¶Gets or sets the figure independent variable label
Type: string or None
Raises: (when assigned)
- RuntimeError (Argument `indep_var_label` is not valid)
- RuntimeError (Figure object is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
indep_var_units
¶Gets or sets the figure independent variable units
Type: string or None
Raises: (when assigned)
- RuntimeError (Argument `indep_var_units` is not valid)
- RuntimeError (Figure object is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
log_indep_axis
¶Gets or sets the figure logarithmic independent axis flag; indicates whether the independent axis is linear (False) or logarithmic (True)
Type: boolean
Raises: (when assigned)
- RuntimeError (Argument `log_indep_axis` is not valid)
- RuntimeError (Figure object is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
panels
¶Gets or sets the figure panel(s),
None
if no panels have been specified
Type: pplot.Panel, list of pplot.panel or None
Raises: (when assigned)
- RuntimeError (Argument `fig_height` is not valid)
- RuntimeError (Argument `fig_width` is not valid)
- RuntimeError (Argument `panels` is not valid)
- RuntimeError (Figure object is not fully specified)
- RuntimeError (Figure size is too small: minimum width [min_width], minimum height [min_height])
- TypeError (Panel [panel_num] is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
title
¶Gets or sets the figure title
Type: string or None
Raises: (when assigned)
- RuntimeError (Argument `title` is not valid)
- RuntimeError (Figure object is not fully specified)
- ValueError (Figure cannot be plotted with a logarithmic independent axis because panel [panel_num], series [series_num] contains negative independent data points)
Contracts pseudo-types¶
Introduction¶
The pseudo-types defined below can be used in contracts of the PyContracts or Pexdoc libraries. As an example, with the latter:
>>> from __future__ import print_function >>> import pexdoc >>> from pplot.ptypes import interpolation_option >>> @pexdoc.pcontracts.contract(ioption='interpolation_option') ... def myfunc(ioption): ... print('Option received: '+str(ioption)) ... >>> myfunc('STEP') Option received: STEP >>> myfunc(35) Traceback (most recent call last): ... RuntimeError: Argument `ioption` is not valid
Alternatively each pseudo-type has a checker function associated with it that can be used to verify membership. For example:
>>> import pplot.ptypes >>> # None is returned if object belongs to pseudo-type >>> pplot.ptypes.interpolation_option('STEP') >>> # ValueError is raised if object does not belong to pseudo-type >>> pplot.ptypes.interpolation_option(3.5) Traceback (most recent call last): ... ValueError: [START CONTRACT MSG: interpolation_option]...
Description¶
ColorSpaceOption¶
Import as color_space_option
. String representing a Matplotlib color space, one 'binary'
, 'Blues'
,
'BuGn'
, 'BuPu'
, 'GnBu'
, 'Greens'
,
'Greys'
, 'Oranges'
, 'OrRd'
, 'PuBu'
,
'PuBuGn'
, 'PuRd'
, 'Purples'
, 'RdPu'
,
'Reds'
, 'YlGn'
, 'YlGnBu'
, 'YlOrBr
‘,
'YlOrRd'
or None
InterpolationOption¶
Import as interpolation_option
. String representing an interpolation
type, one of 'STRAIGHT'
, 'STEP'
, 'CUBIC'
,
'LINREG'
(case insensitive) or None
LineStyleOption¶
Import as line_style_option
. String representing a Matplotlib line
style, one of '-'
, '--'
, '-.'
, ':'
or
None
Checker functions¶
-
pplot.ptypes.
color_space_option
(obj)¶ Validates if an object is a ColorSpaceOption pseudo-type object
Parameters: obj (any) – Object
Raises: - RuntimeError (Argument `*[argument_name]*` is not valid). The token *[argument_name]* is replaced by the name of the argument the contract is attached to
- RuntimeError (Argument `*[argument_name]*` is not one of ‘binary’, ‘Blues’, ‘BuGn’, ‘BuPu’, ‘GnBu’, ‘Greens’, ‘Greys’, ‘Oranges’, ‘OrRd’, ‘PuBu’, ‘PuBuGn’, ‘PuRd’, ‘Purples’, ‘RdPu’, ‘Reds’, ‘YlGn’, ‘YlGnBu’, ‘YlOrBr’ or ‘YlOrRd). The token *[argument_name]* is replaced by the name of the argument the contract is attached to
Return type: None
-
pplot.ptypes.
interpolation_option
(obj)¶ Validates if an object is an InterpolationOption pseudo-type object
Parameters: obj (any) – Object
Raises: - RuntimeError (Argument `*[argument_name]*` is not valid). The token *[argument_name]* is replaced by the name of the argument the contract is attached to
- RuntimeError (Argument `*[argument_name]*` is not one of [‘STRAIGHT’, ‘STEP’, ‘CUBIC’, ‘LINREG’] (case insensitive)). The token *[argument_name]* is replaced by the name of the argument the contract is attached to
Return type: None
-
pplot.ptypes.
line_style_option
(obj)¶ Validates if an object is a LineStyleOption pseudo-type object
Parameters: obj (any) – Object
Raises: - RuntimeError (Argument `*[argument_name]*` is not valid). The token *[argument_name]* is replaced by the name of the argument the contract is attached to
- RuntimeError (Argument `*[argument_name]*` is not one of [‘-‘, ‘–’, ‘-.’, ‘:’]). The token *[argument_name]* is replaced by the name of the argument the contract is attached to
Return type: None