one_d¶
Class summary¶
MarkersDashesColors (**kwargs) |
Nice looking markers, dashed lines, and colors for matplotlib line plots |
Function summary¶
apply_dict_to_object (obj, dic) |
Apply a dict of properties to a matplotlib object. |
apply_markevery_to_sequence_of_lines (lines) |
Apply markevery property to sequence of matplotlib lines |
copy_dict (source_dict, diffs) |
Returns a copy of source_dict, updated with the new key-value pairs in diffs dict. |
iterable_method_call (iterable, method, ...) |
Call a method on each element of an iterable |
pleasing_defaults () |
Alter some matplotlib rcparams defaults to be visually more appealing |
plot_data_in_grid (fig, data, gs[, gs_index, ...]) |
Make a subplot for each set of data |
plot_generic_loads (load_triples, load_names) |
Plot loads that come in load_vs_time-load_vs_depth-omega_phase form |
plot_single_material_vs_depth (z_x, xlabels) |
Plot side by side property vs depth graphs |
plot_vs_depth (x, z[, line_labels, H, ...]) |
Plot z vs x for various t values |
plot_vs_time (t, y[, line_labels, prop_dict]) |
Plot y vs t with some options |
rgb_shade (rgb[, factor, scaled]) |
Apply shade (darken) to a red, green, blue (rgb) triplet |
rgb_tint (rgb[, factor, scaled]) |
Apply tint (lighten) to a red, green, blue (rgb) triplet |
row_major_order_reverse_map (shape[, ...]) |
Map an index to a position in a row-major ordered array by reversing dims |
save_figure (fig[, fname, ext, dpi]) |
Save a figure to a file in multiple formats |
split_sequence_into_dict_and_nondicts (*args) |
Separate dict and non-dict items. |
xylabel_subplots (fig[, y_axis_labels, ...]) |
Set x-axis label and y-axis label for each sub plot in figure |
Module listing¶
Routines to produce some matplotlib plots for one dimesional data.
One dimensional data is basically x-y data. (i.e. no contour plot needed)
-
class
geotecha.plotting.one_d.
MarkersDashesColors
(**kwargs)[source]¶ Bases:
object
Nice looking markers, dashed lines, and colors for matplotlib line plots
Use this object to create a list of style dictionaries. Each style dict can be unpacked when passed to the matplotlib.plot command. Each dict contains the appropriate keywords to set the marker, dashes, and color properties. You can turn the list into a cycle using itertools.cycle To see the marker, dashes, and color options run the demo_options’ method. To choose a subset of styles see the `__call__ method. To view what the chosen styles actually look like run the construct_styles’ and the `demo_styles method
Parameters: **kwargs : keyword arguments
key value pairs to override the default_marker. e.g. color=(1.0,0,0) would change the default line and marker color to red. markersize=8 would change all marker sizes to 8. Most likely value to change are color, markersize, alpha. Defult values of the default_marker are:
key value markersize 5 markeredgecolor almost_black, ‘#262626’ markeredgewidth 1 markerfacecolor almost_black, ‘#262626’ alpha 0.9 color almost_black, ‘#262626’ Attributes
almost_black (str) hex string representing the default color, almost black ‘#262626’. color (matplotlib color) Default color of markers and lines. Default color=`almost_black`. dashes (list of tuples) List of on, off tuples for use with matplotlib dashes. See construct_dashes method. colors (list of tuples) List of rgb tuples describing colors. See construct_dashes. markers (list of dict) List of dict describing marker properties to pass to matplotlib.plot command. See construct_markers method. default_marker (dict) Default properties for markers. These defaults will be overridden by the values in markers. Before initialization default_marker has the following keys. Methods
__call__
([markers, dashes, marker_colors, ...])List of styles to unpack in matplotlib.plot for pleasing lines/markers construct_colors
()Populate self.colors: a list of rgb colors construct_dashes
()List of on, off tuples for use with matplotlib dashes construct_markers
()Populate self.markers: a list of dict that define a matplotlib marker construct_styles
([markers, dashes, ...])Calls self.__call__ and assigns results to self.styles demo_options
()Show a figure with all the marker, dashes, color options available demo_styles
()Show a figure of all the styles in self.styles merge_default_markers
()Merge self.default_marker dict with each dict in self.markers shade_colors
([factor])Darken all colors by factor tint_colors
([factor])Lighten all colors by factor -
almost_black
= '#262626'¶
-
construct_markers
()[source]¶ Populate self.markers: a list of dict that define a matplotlib marker
run self.merge_default_markers after running self.construct_markers so that default properties are applied properly.
-
-
geotecha.plotting.one_d.
apply_dict_to_object
(obj, dic)[source]¶ Apply a dict of properties to a matplotlib object.
Note the object must support set_<property_name> methods If obj and d are lists then the each dic will be applied to the corresponding obj.
Parameters: obj : matplotlib object or list of
Object to set properties in. Typically a matplotlib.lines.Line2D instance.
dic : dict or list of dict
A dictionary or properties to apply to the object. e.g for a matplotlib.lines.Line2D dict keys might be ‘marker’, or ‘linestyle’ etc. i.e any kwarg you would pass to plt.plot. Note that if a key in dic does not correspond to a obj.set_key method then it will be ignored.
-
geotecha.plotting.one_d.
apply_markevery_to_sequence_of_lines
(lines, markevery=None, random_start=True, seed=None)[source]¶ Apply markevery property to sequence of matplotlib lines
Allows for a random start so that marker on different lines do not line up.
Parameters: lines : sequence of matplotlib lines
Lines to apply markevery to.
markevery : int or float, optional
Value of markevery property. Default markevery=None, i.e. markevery will be turned off and all points will have markers.
random_start : True/False
If True then first marker shown will be random between start marker and the markevery property. Default random_start=True.
seed : int, optional
Random seed. Default seed=None which does not specify the random seed.
-
geotecha.plotting.one_d.
copy_dict
(source_dict, diffs)[source]¶ - Returns a copy of source_dict, updated with the new key-value
- pairs in diffs dict.
Parameters: source_dict : dict
Source dictionary.
diffs : dict
Dictionary with which to update source_dict.
Returns: out : dict
Shallow copy of source_dict updated with diffs dict.
References
http://stackoverflow.com/a/5551706/2530083
Examples
>>> d = copy_dict({'a':7, 'b':12}, {'c':13}) >>> d['a']; d['b']; d['c'] 7 12 13
>>> d = copy_dict({'a':7, 'b':12}, {'a':21, 'c':13}) >>> d['a']; d['b']; d['c'] 21 12 13
-
geotecha.plotting.one_d.
iterable_method_call
(iterable, method, unpack, *args)[source]¶ Call a method on each element of an iterable
iterable[i].method(arg)
Parameters: iterable : sequence etc.
Iterable whos members will have thier attribute changed.
method : string
Method to call.
unpack : bool
If True then each member of *args will be unpacked before passing to method.
*args : positional arguments
If a single positional argument then all members of iterable will have their method called with the same single argument. If more that one positional argument then iterable[0].method will be called with args[0], iterable[1].method will be set to args[1] etc. Skip elements by having corresponding value of *args=None.
-
geotecha.plotting.one_d.
pleasing_defaults
()[source]¶ Alter some matplotlib rcparams defaults to be visually more appealing
References
Many of the ideas/defaults/code come from Olga Botvinnik [R123], and her prettyplot package [R124].
[R123] (1, 2) http://blog.olgabotvinnik.com/post/58941062205/prettyplotlib-painlessly-create-beautiful-matplotlib [R124] (1, 2) http://olgabot.github.io/prettyplotlib/
-
geotecha.plotting.one_d.
plot_data_in_grid
(fig, data, gs, gs_index=None, sharex=None, sharey=None)[source]¶ Make a subplot for each set of data
Parameters: fig : matplotlib.Figure
Figure to create subplots in.
data : sequence of sequence of 2 element sequence
data[i] = Data for the ith subplot. data[i][j] = jth (x, y) data set for the ith subplot. Each set of (x, y) data will be plotted using matplotlib.plot fn e.g. data=[([x0, y0],), ([x1, y1],), ([x2a, y2a], [x2b, x2b])] Note that data[i][j] will be split into list of all the non-dict items and a merged dict of all the dict items. Both the list and the merged dict will be unpacked and passed to the plot_type function. This allows passing of keyword arguments. If one of the dict keys is ‘plot_type’ it’s value should be a string indicating a method of matplotlib.Axes that can be used to create the subplot. If ‘plot_type’ is not found then the default matplotlib.Axes.plot will be used. Be careful when using () to group data if there is only one item in the (item) then they are just parentheses and you are just saying ‘item’; put a comma after the item to make it a tuple which is usually what you want when specifying data in this function.
gs : matplotlib.gridspec.GridSpec instance
Defines the grid in which subplots will be created.
gs_index : List of int or list of slice, optional
Specifies the position within gs that each data set will be plotted Positions can be specified by 1) an integer which will correspond to row-major ordering in the grid (e.g. for a 3x3 grid, index 3 will be second row, first column), or 2) a tuple of (row,column), or 3) a slice (e.g. index of np.s_[:1,:1] will span from first row, first column to second row, second column). Another slice method is slice(3,7) which will span from position 3 to position 7. Default gs_index=None subplots are added in row-major ordering.
sharex : sequence of int
Subplot index to share x-axis with. Default sharex=None i.e. no sharing. To skip a subplot put None as the corresponding element of sharex. If only one value is given and ther is more than one data set then all subplots will share the given axis. Note that the axis to share must already have been created.
sharey : sequence of int
Subplot index to share y-axis with. Default sharey=None i.e. no sharing. To skip a subplot put None as the corresponding element of sharey. If only one value is given and ther is more than one data set then all subplots will share the given axis. Note that the axis to share must already have been created.
Returns: ax : List of
matplotlib.pyplot.Axes
instances. Don’t beconfused with normal meaning of ‘ax’, this ax is a list of Axes, not just one.
Notes
You may be wondering how to apply axes labels and such. Do something like [a.set_xlabel(v) for a, v in zip(fig.get_axes(), [xlabel1, xlabel2, ...])]
-
geotecha.plotting.one_d.
plot_generic_loads
(load_triples, load_names, ylabels=None, trange=None, H=1.0, RLzero=None, prop_dict={})[source]¶ Plot loads that come in load_vs_time-load_vs_depth-omega_phase form
For each load_triple (i.e. each load type) two plots will be made side by side: a load_vs_time plot; and a load_vs_depth plot. the different load types will appear one under the other.
- ::
- Load Magnitude Depth ^ ^ | ..... | * | . | * | . . . . | * | . | * | . | * ———————>Time ———>Load factor
Parameters: load_triples : list of list of 3 element tuples
(load_vs_time, load_vs_depth, load_omega_phase) PolyLines. load_triples[i] will be a list of load triples for the ith plot load_triples[i][j] will be the jth load triple for the ith plot. The load_vs_depth can also be a two element tuple containing a list/array of depth values and a list/array of load values. The load_vs_time can also be a two element tuple containing a list/array of time values and a list/array of load values.
load_names : list of string
string to prepend to legend entries for each load
ylabels : list of string, optional
y labels for each of the axes, Default ylabels=None i.e. y0, y1, y2 etc.
trange : 2 element tuple, optional
(tmin, tmax) max and min times to plot loads for. Default trange=None i.e. t limits will be worked out from data.
H : float, optional
Height of soil profile. Default H=1.0. Used to transform normalised depth to actual depth.
RLzero : float, optional
Reduced level of the top of the soil layer. If RLzero is not None then all depths (in plots and results) will be transformed to an RL by RL = RLzero - z*H. If RLzero is None (i.e. the default) then all actual depths will be reported z*H (i.e. positive numbers).
prop_dict : dict of dict, optional
Dictionary containing certain properties used to set various plot options.
prop_dict option description fig_prop dict of prop to pass to plt.figure. Defaults include: figsize=(7.05, 1.57 * no.of.loads) styles List of dict. Each dict is for one line. Each dict contains kwargs for plt.plot. SeeMarkersDashesColors. Defaults give black and white markersize 5. time_axis_label Label for x axis in load_vs_time plots. Default=’Time’ depth_axis_label Label for y axis in load_vs_depth plot Default=”Depth, z” or “RL” depending on RLzero. has_legend True or False. Default = True. legend_prop dict of prop to pass to ax.legend. Defaults include: title=’Load’ fontsize=9 Returns: fig : matplolib.Figure
Figure with plots.
-
geotecha.plotting.one_d.
plot_single_material_vs_depth
(z_x, xlabels, H=1.0, RLzero=None, prop_dict={})[source]¶ Plot side by side property vs depth graphs
x1 x2 x3 -----------> -----------> ------------> | . | . | . | | . | . | . | | . | . | . | | . | . | . | | . | . | . | | . | . | . | v v v depth
Parameters: z_x : list of PolyLine
List of value_vs_depth PolyLines.
xlabels : list of string
List of x-axis labels.
H : float, optional
Height of soil profile. Default H=1.0. Used to transform normalised depth to actual depth.
RLzero : float, optional
Reduced level of the top of the soil layer. If RLzero is not None then all depths (in plots and results) will be transformed to an RL by RL = RLzero - z*H. If RLzero is None (i.e. the default) then all depths will be reported z*H (i.e. positive numbers).
prop_dict : dict of dict, optional
Dictionary containing certain properties used to set various plot options:
prop_dict option description fig_prop dict of prop to pass to plt.figure. defaults include: figsize=(7.05, 4.4) styles List of dict. Each dict is for one line. Each dict contains kwargs for plt.plot See MarkersDashesColors defaults give black and white markersize 5 xlabel x-axis label. default = ‘Time’ ylabel y-axis label. default = ‘Depth, z’ or ‘RL’ depending on RLzero.
-
geotecha.plotting.one_d.
plot_vs_depth
(x, z, line_labels=None, H=1.0, RLzero=None, prop_dict={})[source]¶ Plot z vs x for various t values
Originally used for plotting things like excess pore pressure vs depth
--------------------> value |.* | . * | . * | . * | . * | . * v depth
Parameters: x : one or two dimensional ndarray
y values to plot. Basically plt.plot(t, y) will be used
z : one d array of float
Depth values.
line_labels : list of string, optional
Label for each line in y. Default line_labels=None, i.e. no line labels.
H : float, optional
Height of soil profile. Default H=1.0. Used to transform normalised depth to actual depth.
RLzero : float, optional
Reduced level of the top of the soil layer. If RLzero is not None then all depths (in plots and results) will be transformed to an RL by RL = RLzero - z*H. If RLzero is None (i.e. the default) then actual depths will be reported z*H (i.e. positive numbers).
prop_dict : dict of dict, optional
Dictionary containing certain properties used to set various plot options.
prop_dict option description fig_prop dict of prop to pass to plt.figure. defaults include: figsize=(7.05, 4.4) styles List of dict. Each dict is for one line. Each dict contains kwargs for plt.plot See MarkersDashesColors defaults give black and white markersize 5 xlabel x-axis label. Default = ‘x’. ylabel y-axis label. Default = ‘Depth, z’ or ‘RL’. depending on RLzero. has_legend True or False. default is True legend_prop dict of prop to pass to ax.legend defaults include: title=’Depth interval’ fontsize=9 Returns: fig : matplolib.Figure
Figure with plots.
-
geotecha.plotting.one_d.
plot_vs_time
(t, y, line_labels=None, prop_dict={})[source]¶ Plot y vs t with some options
Originally used for plotting things like average excess pore pressure vs time.
y ^ | ....... | . | . . . . *** | . * * * | .* ***** --------------------->Time
Parameters: t : np.array
Time values.
y : one or two dimensional ndarray
y values to plot. basically plt.plot(t,y) will be used.
line_labels : list of string, optional
Label for each line in y. Defaultline_labels=None, i.e. no labels.
prop_dict : dict of dict, optional
Dictionary containing certain properties used to set various plot options.
prop_dict option description fig_prop dict of prop to pass to plt.figure. Defaults include: figsize=(7.05, 4.4) styles List of dict. Each dict is for one line. Each dict contains kwargs for plt.plot See MarkersDashesColors defaults give black and white markersize 5 xlabel x-axis label. default=’Time’. ylabel y-axis label. default = ‘y’. has_legend True or False. default = True. legend_prop dict of prop to pass to ax.legend Defaults include: title=’Depth interval’ fontsize=9 Returns: fig : matplolib.Figure
Figure with plots.
-
geotecha.plotting.one_d.
rgb_shade
(rgb, factor=1, scaled=True)[source]¶ Apply shade (darken) to a red, green, blue (rgb) triplet
If rgba tuple is given the ‘a’ value is not altered.
Parameters: rgb : tuple
Triplet of rgb values. Note can be an rgba value.
factor : float
Between 0 and 1. Factor by which to shade. Default factor=1.
scaled : bool
If True then assumes RGB values aare scaled between 0, 1. If False rgb values are between 0 and 255. Default scaled=True.
Returns: rgb_new : tuple
New tuple of rgb (or rgba) values.
See also
rgb_tint
- Lighten an rgb triplet.
Examples
>>> x=rgb_shade((0.4, 0.8, 0.2), factor=0.5) >>> '{:.2f}, {:.2f}, {:.2f}'.format(*x) '0.20, 0.40, 0.10'
-
geotecha.plotting.one_d.
rgb_tint
(rgb, factor=0, scaled=True)[source]¶ Apply tint (lighten) to a red, green, blue (rgb) triplet
If rgba tuple is given the ‘a’ value is not altered.
Parameters: rgb : tuple
Triplet of rgb values. Note can be an rgba value.
factor : float
Between 0 and 1. Factor by which to tint. Default factor=0.
scaled : bool
If True then assumes RGB values aare scaled between 0, 1. If False rgb values are between 0 and 255. Default scaled=True.
Returns: rgb_new : tuple
New tuple of rgb ( or rgba).
See also
rgb_shade
- Darken an rgb triplet.
Examples
>>> x=rgb_tint((0.4, 0.8, 0.2), factor=0.5) >>> '{:.2f}, {:.2f}, {:.2f}'.format(*x) '0.70, 0.90, 0.60'
>>> x=rgb_tint((155, 205, 55), factor=0.5, scaled=False) >>> '{:.2f}, {:.2f}, {:.2f}'.format(*x) '205.00, 230.00, 155.00'
-
geotecha.plotting.one_d.
row_major_order_reverse_map
(shape, index_steps=None, transpose=False)[source]¶ Map an index to a position in a row-major ordered array by reversing dims
e.g. shape=(3,3) |2 1 0| |0 1 2| |5 4 3| --> |3 4 5| |8 7 6| |6 7 8| need 0-->2, 1-->1, 2-->0. i.e. [2 1 0 5 4 3 8 7 6]. Use row_major_order_reverse_map((3,3), (1,-1))
Use this to essentially change the subplot ordering in a matplotlib figure. Say I wanted sub_plot ordering as in the left arrangement of the above example. use mymap = row_major_order_reverse_map((3,3), (1,-1)). If I wanted to plot in my position 5 I would pass mymap[5] to the figure.
Parameters: shape : tuple
Shape of array, e.g. (rows, columns)
index_steps : list of 1 or -1, optional
Traverse each array dimension in steps f index_steps. Default index_steps=None i.e. all dims traversed in normal order. e.g. for 3 d array, index_steps=(1,-1, 1) would mean 2nd dimension would be reversed.
transpose : True/False, optional
When True, transposes indexes (final operation). Default transpose=False.
Returns: pos : 1d ndarray
Array that maps index to position in row-major ordered array
Notes
A use for this is positioning subplots in a matplotlib gridspec
Examples
>>> row_major_order_reverse_map(shape=(3, 3), index_steps=None, transpose=False) array([0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> row_major_order_reverse_map(shape=(3, 3), index_steps=(-1, 1), transpose=False) array([6, 7, 8, 3, 4, 5, 0, 1, 2]) >>> row_major_order_reverse_map(shape=(3, 3), index_steps=(1, -1), transpose=False) array([2, 1, 0, 5, 4, 3, 8, 7, 6]) >>> row_major_order_reverse_map(shape=(3, 3), index_steps=(-1, -1), transpose=False) array([8, 7, 6, 5, 4, 3, 2, 1, 0]) >>> row_major_order_reverse_map(shape=(3, 3), index_steps=None, transpose=True) array([0, 3, 6, 1, 4, 7, 2, 5, 8])
-
geotecha.plotting.one_d.
save_figure
(fig, fname='fig', ext=['pdf', 'eps', 'png'], dpi=1200)[source]¶ Save a figure to a file in multiple formats
Figure will be saved in as fname.ext where ext is each of the extenstions in the ext parameter.
Parameters: fig : matplotlib.Figure object
Figure to save
fname : str, optional
filepath to save to WITHOUT extension, default fname=’fig’.
ext : list of str, optional
List of file extensions to save. Must be one of the matplolib save as file types. default ext=[[‘pdf’,’eps’,’png’].
dpi : int, optional
dpi setting to save png etc figures as. Default dpi=1200.
-
geotecha.plotting.one_d.
split_sequence_into_dict_and_nondicts
(*args)[source]¶ Separate dict and non-dict items. Merge dicts and merge non-dicts
Elements are combined in the order that they appear. i.e. non-dict items will be appended to a combined list as they are encounterd. Repeated dict keys will be overridded by the latest value.
Parameters: *args : one or more positional items
Mixture of dict and non-dict.
Returns: merged_non_dict : list
List of non dictionary items.
merged_dict : dict
Merged dictionary.
-
geotecha.plotting.one_d.
xylabel_subplots
(fig, y_axis_labels=None, x_axis_labels=None)[source]¶ Set x-axis label and y-axis label for each sub plot in figure
Note: labels are applied to axes in the order they were created, which is not always the way they appear in the figure.
Parameters: fig : matplotlib.Figure
Figure to apply labels to.
y_axis_labels : sequence
Label to place on y-axis of each subplot. Use None to skip a subplot. Default y_axis_label=None
x_axis_labels : sequence
Label to place on x-axis of each subplot. Use None to skip a subplot. Default x_axis_label=None.