mcPlot#
Standard plotting class of Matthias Cuntz.
It has the same functionality as the old mc_template.py by Matthias Cuntz but uses the object-oriented approach of st_template.py of Stephan Thober.
It allows plotting on screen, into PDF and PNG files, as well as in HTML files as a wrapper for PNG images or using hvplot.
It is optimised for publication ready plots, either on white or black background.
The simplest way to use mcPlot is to extend the class:
import numpy as np
from pyjams import mcPlot
class PlotIt(mcPlot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# change e.g. colors
self.lcol1 = 'cyan'
# reset global values after colour changes, etc.
self.set_matplotlib_rcparams()
def read_data(self):
# do something
self.dat = np.arange(10)
def plot_fig_1(self):
import matplotlib.pyplot as plt
self.ifig += 1
fig = plt.figure(self.ifig)
sub = fig.add_axes([0.125, 0.667, 0.3375, 0.233])
larr = sub.plot(self.dat)
plt.setp(larr[-1], linestyle='-', linewidth=self.lwidth,
marker='', color=self.lcol1)
self.plot_save(fig)
def plot_fig_2(self):
import matplotlib.pyplot as plt
self.ifig += 1
fig = plt.figure(self.ifig)
sub = fig.add_axes([0.125, 0.667, 0.3375, 0.233])
larr = sub.plot(2*self.dat)
plt.setp(larr[-1], linestyle='-', linewidth=self.lwidth,
marker='', color=self.lcols[-1])
self.plot_save(fig)
if __name__ == '__main__':
iplot = PlotIt(desc='Test mcPlot',
argstr='No argument wanted')
iplot.read_data()
iplot.plot_fig_1()
iplot.plot_fig_2()
iplot.close()
Then call the script with -h to see the command line options.
This module was written by Matthias Cuntz while at Institut National de Recherche pour l’Agriculture, l’Alimentation et l’Environnement (INRAE), Nancy, France.
- copyright:
Copyright 2020- Matthias Cuntz, see AUTHORS.rst for details.
- license:
MIT License, see LICENSE for details.
The following classes are provided:
|
Standard plotting class of Matthias Cuntz |
- History
Written Sep 2020 by Matthias Cuntz (mc (at) macu (dot) de)
Write standard output file into current folder, Nov 2021, Matthias Cuntz
Change from NCL amwg color palette to pyjams amwg, May 2021, Matthias Cuntz
Add **kwargs to plot_save, May 2022, Matthias Cuntz
Add self.transparent to pdf output in plot_save, May 2022, Matthias Cuntz
Add –transparent as a standard option, May 2022, Matthias Cuntz
Add left, bottom, top to standard layout options, Jul 2022, Matthias Cuntz
Add –dpi as a standard option, Jan 2023, Matthias Cuntz
Use helper.filebase, Mar 2023, Matthias Cuntz
Replace plotly with hvplot, May 2023, Matthias Cuntz
Set filename without suffix as default plot name, Jun 2023, Matthias Cuntz
Removed space from print of plot filename, Jun 2023, Matthias Cuntz
Set default options if not given on command line, Jan 2024, Matthias Cuntz
Add method print_layout_options, Mar 2024, Matthias Cuntz
Use DejaVuSans and DejaVueSerif as standard fonts if not LaTeX because they come with matplotlib, May 2024, Matthias Cuntz
parents argument to ArgumentParser, Jul 2024, Matthias Cuntz
- class mcPlot(desc=None, argstr=None, parents=[])[source]#
Bases:
object
Standard plotting class of Matthias Cuntz
Upon initialisation, the command line arguments are gathered (get_command_line_arguments), the output type is set (set_output_type), standard layout options are added to self (set_layout_options), global rcParams are set for Matplotlib (set_matplotlib_rcparams), and the output plotting file is opened (plot_begin).
- desc#
Description for command line parser, which will be shown when called with -h.
- Type:
string, optional
- argstr#
String given as description for the positional arguments.
- Type:
string, optional
- parents#
ArgumentParser or list of ArgumentParser objects whose arguments should also be included. Note, these parsers should be initialised with add_help=False. Otherwise, the ArgumentParser will see two -h/–help options and raise an error.
- Type:
ArgumentParser or list, optional
- get_command_line_arguments(desc=None, argstr=None, parents=[])[source]#
Standard command line parser with the default arguments such as plot type, filename, etc. If extra arguments are needed, one can pass an ArgumentParser as parent, which was initialised with add_help=False.
- plot_end() or plot_stop() or plot_close() or end() or stop()[source]#
Finish, closing opened output files.
- set_layout_options()[source]#
Sets the colours and styles that can be used in plots. One can either copy this routine into the extending class and adapt it, or add a new method that resets some of the layout options and call it in the initialisation of the extending class, or simply set layout options in the initialisation of the extending class.
Notes
Several more methods are defined, which should probably not be changed.
- plot_begin() or plot_start()
Open output file and similar at the beginning.
- plot_test()
A simple plot as an example.
- print_layout_options(rcparams=False)
Prints current layout options and optionally matplotlib’’s rcParams.
- set_matplotlib_rcparams()
Set rcParams of Matplotlib depending on output type, and chosen layout. rcParams can also be re-set in the initialisation of the extending class.
- set_output_type()
Set the format of the output such as pdf or png.
Examples
The simplest way to use mcPlot is to extend the class:
import numpy as np from pyjams import mcPlot class PlotIt(mcPlot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # change e.g. colors self.lcol1 = 'cyan' def read_data(self): # do something self.dat = np.arange(10) def plot_fig_1(self): import matplotlib.pyplot as plt self.ifig += 1 fig = plt.figure(self.ifig) sub = fig.add_axes([0.125, 0.667, 0.3375, 0.233]) larr = sub.plot(self.dat) plt.setp(larr[-1], linestyle='-', linewidth=self.lwidth, marker='', color=self.lcol1) self.plot_save(fig) def plot_fig_2(self): import matplotlib.pyplot as plt self.ifig += 1 fig = plt.figure(self.ifig) sub = fig.add_axes([0.125, 0.667, 0.3375, 0.233]) larr = sub.plot(2*self.dat) plt.setp(larr[-1], linestyle='-', linewidth=self.lwidth, marker='', color=self.lcols[-1]) self.plot_save(fig) if __name__ == '__main__': iplot = PlotIt(desc='Test mcPlot') iplot.read_data() iplot.plot_fig_1() iplot.plot_fig_2() iplot.close()
Then call the script with -h to see the command line options.
Methods
close
()Alias for plot_end()
end
()Alias for plot_end()
get_command_line_arguments
([desc, argstr, ...])Standard command line parser with default arguments such as plot type, filename, etc.
Alias for plot_end()
plot_end
()Finish plotting
plot_save
(fig, **kwargs)Save figure into output file
Alias for plot_begin()
Alias for plot_end()
A simple test plot
print_layout_options
([rcparams])Print the current layout options
Standard layout options that can be used in plotting methods
Set rcParams depending on output type and other options such as using LaTeX, serif fonts, etc.
Set type of chosen output.
- get_command_line_arguments(desc=None, argstr=None, parents=[])[source]#
Standard command line parser with default arguments such as plot type, filename, etc.
If extra arguments are needed, one should copy this routine into an extending class and adapt it to its needs, keeping the existing optional arguments.
- Parameters:
desc (string, optional) – Description for command line parser, which will be shown when called with -h.
argstr (string, optional) – String given as description for the positional arguments.
parents (ArgumentParser or list, optional) – ArgumentParser or list of ArgumentParser objects whose arguments should also be included. Note, these parsers should be initialised with add_help=False. Otherwise, the ArgumentParser will see two -h/–help options and raise an error.
Notes
Standard command line arguments are:
positional arguments: args Text will be replaced by `argstr`. optional arguments: -h, --help show this help message and exit -p plotname, --plotname plotname Name of plot output file for types pdf, html, d3, or hvplot, and name basis for type png (default: calling_filename without extension). -s, --serif Use serif font; default sans serif. -t outtype, --type outtype Output type is pdf, png, html, d3, or hvplot (default: open screen windows). -u, --usetex Use LaTeX to render text in pdf, png and html. -w, --white White lines on transparent or black background; default: black lines on transparent or white background. --dpi number Dots Per inch (DPI) for non-vector output types or rasterized maps in vector output (default: 300). --transparent Transparent figure background (default: black or white).
Examples
iplot = mcPlot(desc="Test Matthias' plotting class.", argstr="directory file")
- plot_save(fig, **kwargs)[source]#
Save figure into output file
- Parameters:
fig (matplotlib.figure.Figure) – Matplotlib figure object. argstr : string, optional
kwargs (dict, optional) – Additional keywords will be passed to savefig for ‘pdf’, ‘png’, and ‘html’; to fig_to_html for ‘d3’, and to save for ‘hvplot’. This overwrites self.transparent, self.bbox_inches, self.pad_inches for ‘pdf’, ‘png’, and ‘html’.
- print_layout_options(rcparams=False)[source]#
Print the current layout options
Examples
Setting layout options in initialisation
pp = pyjams.mcPlot() pp.print_layout_options(rcparams=True)
- set_layout_options()[source]#
Standard layout options that can be used in plotting methods
One can either copy this routine into an extending class and adapt it, or add a new method that resets some of the layout options and call it in the initialisation of an extending class, or simply set layout options in the initialisation of an extending class.
Current layout options are:
Option
Description
self.nrow
number of rows of subplots per figure
self.ncol
number of columns of subplots per figure
self.left
left space on page
self.right
right space on page
self.bottom
lower bottom space on page
self.top
upper top space on page
self.hspace
(horizontal) x-space between subplots
self.vspace
(vertical) y-space between subplots
self.textsize
standard text size
self.dxabc
% of (max-min) shift to the right of left y-axis for a,b,c,… labels
self.dyabc
% of (max-min) shift up from lower x-axis for a,b,c,… labels
self.lwidth
line width
self.elwidth
errorbar line width
self.alwidth
axis line width
self.msize
marker size
self.mwidth
marker edge width
self.fgcolor
foreground colour
self.bgcolor
background colour
self.mcols
list of marker colours
self.mcol1
marker colour 1
self.mcol2
marker colour 2
self.mcol3
marker colour 3
self.mcol4
marker colour 4
self.mcol5
marker colour 5
self.lcol1
list of line colours
self.lcol2
line colour 1
self.lcol3
line colour 2
self.lcol4
line colour 3
self.lcol5
line colour 4
self.lcols
line colour 5
self.ldashes
list of line styles
self.llxbbox
x-anchor legend bounding box
self.llybbox
y-anchor legend bounding box
self.llrspace
spacing between rows in legend
self.llcspace
spacing between columns in legend
self.llhtextpad
pad between the legend handle and text
self.llhlength
length of the legend handles
self.frameon
if True: draw a frame around the legend. If None: use rc
self.dpi
DPI of non-vector figure output
self.transparent
True for transparent background in figure
self.bbox_inches
Bbox in inches. If ‘tight’, try to figure out the tight bbox of the figure
self.pad_inches
Amount of padding when bbox_inches is ‘tight’
Examples
Setting layout options in initialisation
class UsemcPlot(mcPlot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.lcol1 = 'black' self.mynewcol = 'red' # reset global values after colour changes, etc. self.set_matplotlib_rcparams()
- set_matplotlib_rcparams()[source]#
Set rcParams depending on output type and other options such as using LaTeX, serif fonts, etc.
rcParams can be overwritten in the initialisation of an extending class.
Current parameters set are:
Parameter
Options
ps
papersize, usedistiller
figure
figsize, edgecolor, facecolor
text
usetex, latex.preamble, color
font
family, sans-serif, size
savefig
dpi, format, edgecolor, facecolor
axes
linewidth, edgecolor, facecolor, labelcolor, prop_cycle
boxplot
boxprops.color, capprops.color, flierprops.color, flierprops.markeredgecolor, whiskerprops.color
grid
color
lines
linewidth, color
patch
edgecolor
path
simplify
xtick
color
ytick
color
Examples
Setting rcParams in initialisation
class UsemcPlot(mcPlot): def __init__(self, *args, **kwargs): import matplotlib as mpl super().__init__(*args, **kwargs) mpl.rc('grid', color='red') mpl.rcParams['boxplot.boxprops.color'] = 'blue'