matplotcheck package

Submodules

matplotcheck.autograde module

matplotcheck.autograde

Wrapper functions that run and track the passing status of matplotcheck functions and provide formatted results of tests.

matplotcheck.autograde.output_results(results)[source]

Print a formatted message containing the total number of points summed across a list of dictionaries with results from one or more tests

Parameters:results (list of dictionaries with the following keys:) – points : int or float : points assigned based on test results pass : bool : passing status of test function description : str : test function name that was run message : str : custom message returned based on passing status traceback : AssertionError : returned from test function when pass is False
Returns:points – Number of points summed across points in results list
Return type:int or float
matplotcheck.autograde.run_test(func, points, *args, correct_message='default correct', error_message='default error', **kwargs)[source]

Run a pre-defined test function and creates a dictionary containing the results of the test

Parameters:
  • func (function or method) – Pre-defined test function to run
  • points (int or float) – Number of points assigned for passing test
  • *args – Variable arguments passed to test function
  • correct_message (str) – Custom message returned with passing test
  • error_message (str) – Custom message returned with failing test
  • **kwargs – Keyword arguments passed to test function
Returns:

results – points : int or float : points assigned based on test results pass : bool : passing status of test function description : str : test function name that was run message : str : custom message returned based on passing status traceback : AssertionError : returned from test function when pass is False

Return type:

dict with the following keys:

matplotcheck.base module

matplotcheck.base

Base plot checking class and methods that should apply to all plots whether they are spatial or not.

exception matplotcheck.base.InvalidPlotError[source]

Bases: Exception

class matplotcheck.base.PlotTester(ax)[source]

Bases: object

Object to grab elements from Matplotlib plots Temporarily removing parameters and returns as it’s breaking sphinx

Parameters:axis (mpl axis object) –
assert_axis_label_contains(axis='x', strings_expected=None, message_default='{1}-axis label does not contain expected string: {0}', message_or='{1}-axis label does not contain at least one of: {0}', message_not_displayed='Expected {0} axis label is not displayed')[source]

Asserts that the axis label contains the expected strings from strings_expected. Tests x or y axis based on ‘axis’ param.

Parameters:
  • axis (string) – One of the following [‘x’,’y’] stated which axis label to be tested
  • strings_expected (list) – Any string in strings_expected must be in the axis label for the assertion to pass. If there is a list of strings in strings_expected, at least one of the strings in that list must be in the axis label for the assertion to pass. For example, if strings_expected=['a', 'b', 'c'], then 'a' AND 'b' AND 'c' must be in the title for the assertion to pass. Alternatively, if strings_expected=['a', 'b', ['c', 'd']], then 'a' AND 'b' AND (at least one of: 'c', 'd') must be in the title for the assertion to pass. Case insensitive.
  • message_default (string) – The error message to be displayed if the axis label does not contain a string in strings_expected. If message contains '{1}', it will be replaced with axis. If message contains '{0}', it will be replaced with the first expected string not found in the label.
  • message_or (string) – Similar to message_default, message_or is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in strings_expected. If message contains '{1}', it will be replaced with axis. If message contains '{0}', it will be replaced with the first failing inner list in strings_expected.
  • message_not_displayed (string) – The error message to be displayed if the expected axis label is not displayed. If message_not_displayed contains '{0}', it will be replaced with axis.
Raises:

AssertionError – if axis label does not contain expected strings

assert_axis_off(message='Axis lines are displayed on plot')[source]

Asserts one of the three cases holds true with error message m: 1) axis have been turned off 2) both x and y axis have visibility set to false 3) both x and y axis ticks have been set to empty lists

Parameters:message (string) – The error message to be displayed if the assertion is not met.
Raises:AssertionError – with message m if axis lines are displayed on plot
assert_bin_midpoints(bin_midpoints, message='Did not find expected bin midpoints in plot')[source]

Asserts that the middle values of histogram bins match bin_midpoints.

Parameters:
  • bin_midpoints (list) – A list of numbers representing the expected middles of bin values covered by each consecutive bin (i.e. the midpoint of the bars in the histogram).
  • message (string) – The error message to be displayed if the bin mid point values do not match bin_midpoints
Raises:

AssertionError – if the Values of histogram bins do not match bin_midpoints

assert_bin_values(bin_values, tolerance=0, message='Did not find expected bin values in plot')[source]

Asserts that the values of histogram bins match bin_values.

Parameters:
  • bin_values (list) – A list of numbers representing the expected values of each consecutive bin (i.e. the heights of the bars in the histogram).
  • tolerance (float) – A non-zero value of tol_abs allows an absolute tolerance when checking the bin values. For example, an absolute tolerance of 1 checks that the actual bin values do not differ from the expected bin values by more than 1.
  • message (string) – The error message to be displayed if the bin values do not match bin_values
Raises:

AssertionError – if the Values of histogram bins do not match bin_values

Notes

bin_values can be difficult to know. The easiest way to obtain them may be to create a histogram with your expected data, create a PlotTester object, and use get_bin_values(). get_bin_values() will return exactly the type of list required for bin_values in this method.

assert_caption_contains(strings_expected, message_default='Caption does not contain expected string: {0}', message_or='Caption does not contain at least one of: {0}', message_no_caption='No caption exists in appropriate location')[source]

Asserts that caption contains expected strings from strings_expected.

Parameters:
  • strings_expected (list) – Any string in strings_expected must be in the title for the assertion to pass. If there is a list of strings in strings_expected, at least one of the strings in that list must be in the title for the assertion to pass. For example, if strings_expected=['a', 'b', 'c'], then 'a' AND 'b' AND 'c' must be in the title for the assertion to pass. Alternatively, if strings_expected=['a', 'b', ['c', 'd']], then 'a' AND 'b' AND (at least one of: 'c', 'd') must be in the title for the assertion to pass. Case insensitive.
  • message_default (string) – The error message to be displayed if the axis label does not contain a string in strings_expected. If message contains '{0}', it will be replaced with the first expected string not found in the label.
  • message_or (string) – Similar to message_default, message_or is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in strings_expected. If message contains '{0}', it will be replaced with the first failing inner list in strings_expected.
  • message_no_caption (string) – The error message to be displayed if no caption exists in the appropriate location.
Raises:

AssertionError – if caption does not contain strings matching strings_expected

assert_equal_xlims_ylims(message='xlims and ylims are not equal')[source]

Assert the x and y lims of Axes ax are exactly equal to each other

Parameters:message (string) – The error message to be displayed if the x limits and y limits are equal.
Raises:AssertionError – with message m if limits are not equal
assert_legend_labels(labels_exp, message='Legend does not have expected labels', message_no_legend='Legend does not exist', message_num_labels='I was expecting {0} legend entries, but found {1}. Are there extra labels in your legend?')[source]

Asserts legends on ax have the correct entry labels

Parameters:
  • labels_exp (list of strings) – Each string is an expected legend entry label. Checks that the legend entry labels match exactly (except for case).
  • message (string) – The error message to be displayed if the expected labels are not found.
  • message_no_legend (string) – The error message to be displayed if no legend is found.
  • message_num_labels (string) – The error message to be displayed if there exist a different number of legend labels than expected. If message_num_labels contains '{0}' it will be replaced with the number of labels found. If message_num_labels contains '{1}' it will be replaced with the expected number of labels.
Raises:

AssertionError – if legend labeles do not match labels_exp

Notes

If there are multiple legends, it combines all the legend labels into one set and checks that set against the list labels_exp

assert_legend_no_overlay_content(message='Legend overlays plot window')[source]

Asserts that each legend does not overlay plot window

Parameters:message (string) – The error message to be displayed if the legend overlays the plot window.
Raises:AssertionError – with message m if legend does not overlay plot window
assert_legend_titles(titles_exp, message='Legend title does not contain expected string: {0}', message_num_titles='I was expecting {0} legend titles but instead found {1}')[source]

Asserts legend titles contain expected text in titles_exp list.

Parameters:
  • titles_exp (list of strings) – Each string is expected be be in one legend title. The number of strings is equal to the number of expected legends.
  • message (string) – The error message to be displayed if the legend titles do not match the expected strings. If message contains '{0}', it will be replaced with the first expected string that does not exist in the legend title.
  • message_num_titles (string) – The error message to be displayed if there exist a different number of legend titles than expected. If message_num_titles contains '{0}' it will be replaced with the number of titles found. If message_num_titles contains '{1}' it will be replaced with the expected number of titles.
Raises:

AssertionError – if legend titles do not contain expected text

assert_lims(lims_expected, axis='x', message='Incorrect limits on the {0} axis')[source]

Assert the lims of ax match lims_expected. Tests x or y axis based on ‘axis’ param

Parameters:
  • lims_expected (list of numbers (float or int)) – List of length 2 containing expected min and max vals for axis limits
  • axis (string) – From [‘x’,’y’], which axis to be tested
  • message (string) – The error message to be displayed if the limits of ax do not match the expected limits. If message contains '{0}', it will be replaced with axis.
Raises:

AssertionError – if lims_expected does not match the limits of ax

assert_lims_range(lims_range, axis='x', message_min='Incorrect min limit on the {0} axis', message_max='Incorrect max limit on the {0} axis')[source]

Asserts axis limits fall within lims_range (INCLUSIVE).

Parameters:
  • lims_range (tuple of tuples.) – if axis == ‘x’: first tuple is range the left x limit must be in, second tuple is the range the right x limit must be in if axis == ‘y’: first tuple is range the bottom y limit must be in, second tuple is the range the top x limit must be in
  • axis (string) – from list [‘x’,’y’] declaring which axis to be tested
  • message_min (string) – The error message to be displayed if the limits of ax do not fall within the expected limit minimum. If message contains '{0}', it will be replaced with axis.
  • message_max (string) – The error message to be displayed if the limits of ax do not fall within the expected limit maximum. If message contains '{0}', it will be replaced with the specified axis (i.e. it will be replaced with ‘x’ or ‘y’).
Raises:

AssertionError – if axis limits does not fall within lims_range

assert_line(slope_exp, intercept_exp, check_coverage=True, message_no_line='Expected line not displayed', message_data='Line does not cover data set')[source]

Asserts that there exists a line on Axes ax with slope slope_exp and y-intercept intercept_exp and

Parameters:
  • slope_exp (float) – Expected slope of line
  • intercept_exp (float) – Expeted y intercept of line
  • check_coverage (boolean (default = True)) – If check_coverage is True, function will check that the goes at least from x coordinate min_val to x coordinate max_val. If the line does not cover the entire dataset, and AssertionError with be thrown with message message_data.
  • message_no_line (string) – The error message to be displayed if the line does not exist.
  • message_data (string) – The error message to be displayed if the line exists but does not cover the dataset, and if check_coverage is True.
Raises:

AssertionError – with message message_no_line or message_data if no line exists that covers the dataset.

assert_lines_of_type(line_types, check_coverage=True)[source]

Asserts each line of type in line_types exist on ax

Parameters:
  • line_types (string or list of strings) – Acceptable strings in line_types are as follows ['linear-regression', 'onetoone'].
  • check_coverage (boolean (default = True)) – If check_coverage is True, function will check that the goes at least from x coordinate min_val to x coordinate max_val. If the line does not cover the entire dataset, and AssertionError with be thrown with message message_data.
Raises:

AssertionError – if at least one line of type in line_types does not exist on ax

Notes

If line_types is empty, assertion is passed.

assert_no_legend_overlap(message='Legends overlap eachother')[source]

When multiple legends on ax, asserts that there are no two legends in ax that overlap each other

Parameters:message (string) – The error message to be displayed if two legends overlap.
Raises:AssertionError – with message m if legends overlap
assert_num_bins(num_bins, message='Expected {0} bins in histogram, instead found {1}.')[source]

Asserts number of bins is num_bins.

Parameters:
  • num_bins (int) – Number of bins expected.
  • message (string) – The error message to be displayed if plot does not contain num_bins. If message contains '{0}' it will be replaced with expected number of bins. If message contains '{1}', it will be replaced with the number of bins found.
Raises:

AssertionError – if plot does not contain the expected number of bins

assert_plot_type(plot_type=None, message='Plot is not of type {0}')[source]

Asserts Axes ax contains the type of plot specified in plot_type. if plot_type is None, assertion is passed.

Parameters:
  • plot_type (string) – String specifying the expected plot type. Options: scatter, bar, line
  • message (string) – The error message to be displayed if Plot does not match plot_type. If message contains '{0}', it will be replaced with the epected plot type.
Raises:

AssertionError – if Plot does not match plot_type

assert_string_contains(string, strings_expected, message_default='String does not contain expected string: {0}', message_or='String does not contain at least one of: {0}')[source]

Asserts that string contains the expected strings from strings_expected.

Parameters:
  • strings_expected (list) – Any string in strings_expected must be in the title for the assertion to pass. If there is a list of strings in strings_expected, at least one of the strings in that list must be in the title for the assertion to pass. For example, if strings_expected=['a', 'b', 'c'], then 'a' AND 'b' AND 'c' must be in the title for the assertion to pass. Alternatively, if strings_expected=['a', 'b', ['c', 'd']], then 'a' AND 'b' AND (at least one of: 'c', 'd') must be in the title for the assertion to pass. Case insensitive.
  • message_default (string) – The error message to be displayed if the string does not contain a string in strings_expected. If message contains '{0}', it will be replaced with the first expected string not found in the label.
  • message_or (string) – Similar to message_default, message_or is the error message to be displated if string does not contain at least one of the strings in an inner list in strings_expected. If message contains '{0}', it will be replaced with the first failing inner list in strings_expected.
Raises:

AssertionError – if string does not contain expected strings

assert_title_contains(strings_expected, title_type='either', message_default='Title does not contain expected string: {0}', message_or='Title does not contain at least one of: {0}', message_no_title='Expected title is not displayed')[source]

Asserts that title defined by title_type contains the expected strings from strings_expected.

Parameters:
  • strings_expected (list) – Any string in strings_expected must be in the title for the assertion to pass. If there is a list of strings in strings_expected, at least one of the strings in that list must be in the title for the assertion to pass. For example, if strings_expected=['a', 'b', 'c'], then 'a' AND 'b' AND 'c' must be in the title for the assertion to pass. Alternatively, if strings_expected=['a', 'b', ['c', 'd']], then 'a' AND 'b' AND (at least one of: 'c', 'd') must be in the title for the assertion to pass. Case insensitive.
  • title_type (string) – One of the following strings [“figure”, “axes”, “either”] figure: only the figure title (suptitle) will be tested ‘axes’: only the axes title (suptitle) will be tested ‘either’: either the figure title or axes title will pass this assertion. The combined title will be tested.
  • message_default (string) – The error message to be displayed if the axis label does not contain a string in strings_expected. If message contains '{0}', it will be replaced with the first expected string not found in the label.
  • message_or (string) – Similar to message_default, message_or is the error message to be displated if the axis label does not contain at least one of the strings in an inner list in strings_expected. If message contains '{0}', it will be replaced with the first failing inner list in strings_expected.
  • message_no_title (string) – The error message to be displayed if the expected title is not displayed.
Raises:

AssertionError – if title does not contain expected strings

assert_xlabel_ydata(xy_expected, xcol, ycol, message='Incorrect Data')[source]

Asserts that the numbers in x labels and y values in Axes ax match xy_expected.

Parameters:
  • xy_expected (pandas.DataFrame) – Pandas DataFrame that contains data
  • xcol (string) – Column title containing xaxis data
  • ycol (string) – Column title containing yaxis data
  • message (string) – The error message to be displayed if data in the x-labels and y-values do not match xy_expected.
Raises:

AssertionError – with message m if legends overlap

Notes

This is only testing the numbers in x-axis labels.

assert_xydata(xy_expected, xcol=None, ycol=None, points_only=False, xlabels=False, tolerance=0, message='Incorrect data values')[source]

Asserts that the x and y data of Axes ax matches xy_expected with error message message. If xy_expected = None, assertion is passed.

Parameters:
  • xy_expected (pandas or geopandas dataframe) – (Required) DataFrame contains data expected to be on the plot (axis object)
  • xcol (string) – (Required for non geopandas objects) Title of column in xy_expected containing values along x_axis. If xy_expected contains this data in ‘geometry’, set to None.
  • ycol (String) – (Required for non geopandas objects) The y column name of xy_expected which represents values along the`y_axis` in a plot. If xy_expected contains this data in ‘geometry’ set to None.
  • points_only (boolean,) – Set True to check only points, set False tp check all data on plot.
  • xlabels (boolean) – Set True if using x axis labels rather than x data. Instead of comparing numbers in the x-column to expected, compares numbers or text in x labels to expected.
  • tolerance (float) – A non-zero value of tol_rel allows an absolute tolerance when checking the data. For example, a tolerance of 0.1 would check that the actual data is within 0.1 units of the actual data. Note that the units for datetime data is always days.
  • message (string) – The error message to be displayed if the xy-data does not match xy_expected
Raises:

AssertionError – with message message, if x and y data of Axes ax does not match xy_expected

get_bin_midpoints()[source]

Returns the mid point value of each bin in a histogram

Returns:The number of bins in the histogram
Return type:Int
get_bin_values()[source]

Returns the value of each bin in a histogram (i.e. the height of each bar in a histogram.)

Returns:The number of bins in the histogram
Return type:Int
get_caption()[source]

Returns the text that is located in the bottom right, just below the right side of ax If no text is found in location, None is returned.

Returns:caption – the text that is found in bottom right, None if no text is found
Return type:string
get_legends()[source]

Retrieve the list of legends on ax

Returns:legends – List of matplotlib.legend.Legend objects
Return type:list
get_num_bins()[source]

Gets the number of bins in histogram with a unique x-position.

Returns:Returns the number of bins with a unique x-position. For a normal histogram, this is just the number of bins. If there are two overlapping or stacked histograms in the same matplotlib.axis.Axis object, then this returns the number of bins with unique edges.
Return type:Int
get_slope_yintercept(path_verts)[source]

Returns the y-intercept of line based on the average slope of the line

Parameters:path_verts (list) – List of verticies that make a line on Axes ax
Returns:
  • slope (float) – The average slope of the line defined by path_verts
  • y_intercept (float) – The y intercept of the line defined by path_verts
get_titles()[source]

Returns the suptitle (Figure title) and axes title of ax.

Returns:
  • suptitle (string) – Figure title of the Figure that the ax object is on. If figure title is None, this is an empty string.
  • title (string) – Title on the axes. If title is None, this is an empty string.
get_xy(points_only=False)[source]

Returns a pandas dataframe with columns “x” and “y” holding the x and y coords on Axes ax

Parameters:
  • ax (matplotlib.axes.Axes) – Matplotlib Axes object to be tested
  • points_only (boolean) – Set True to check only points, set False to check all data on plot.
Returns:

df – Pandas dataframe with columns “x” and “y” containing the x and y coords of each point on Axes ax

Return type:

pandas.DataFrame

legends_overlap(b1, b2)[source]

Helper function for assert_no_legend_overlap. True if points of window extents for b1 and b2 overlap, False otherwise

Parameters:
  • b1 (list of lists) – 2x2 array containg numbers, bounding box of window extents
  • b2 (list of lists) – 2x2 array containg numbers, bounding box of window extents
Returns:

overlap – True if bounding boxes b1 and b2 overlap

Return type:

boolean

matplotcheck.cases module

class matplotcheck.cases.PlotBasicSuite(ax, data_exp=None, xcol=None, ycol=None, plot_type=None, line_types=None, xlabels=False, lims_equal=False, title_contains=[], title_type='either', xlabel_contains=[], ylabel_contains=[], caption_strings=[], legend_labels=None, title_points=1, xlab_points=1, ylab_points=1)[source]

Bases: object

A generic object to test a basic 2d Matplotlib plot (scatter, bar, line)

Parameters:
  • ax (Matplotlib Axes to be tested) –
  • data_exp (pandas dataframe containing plot data) –
  • xcol (string column title in data_exp that contains xaxis data) –
  • ycol (string column title in data_exp that contains yaxis data) –
  • plot_type (string from list ["scatter","bar"] of expected plot type) –
  • line_types (list of strings. Acceptable strings in line_types are as) –
  • follows
  • "onetoone"] (["regression",) – if list is empty, assert is passed
  • xlabels (boolean if using x axis labels rather than x data) –
  • lims_equal (boolean expressing if x and y limits are expected to be equal) –
  • title_contains (list of lower case strings where each string is expected to) –
  • in title, barring capitalization. (be) – If value is an empty list: test is just to see that title exists and is not an empty string If value is None: no tests are run
  • title_type (one of the following strings ["figure", "axes", "either"]) – “figure”: only the figure title (suptitle) will be tested “axes”: only the axes title (suptitle) will be tested “either”: either the figure title or axes title will pass this assertion. The combined title will be tested.
  • xlabel_contains (list of lower case strings where each string is expected) –
  • be in x-axis label, barring capitalization. (to) – If value is an empty list: test is just to see that x-axis label exists and is not an empty string If value is None: no tests are run
  • ylabel_contains (list of lower case strings where each string is expected) –
  • be in y-axis label, barring capitalization. (to) – If value is an empty list: test is just to see that y-axis label exists and is not an empty string If value is None: no tests are run
  • caption_string (list of lists. Each internal list is a list of lower case) –
  • where at least one string must be (strings) – found in the caption, barring capitalization if empty list: asserts caption exists and not an empty string if None: no tests are run
  • legend_labels (list of lower case stings. Each string is an expected entry) –
  • in the legend, barring capitalization. (label) –
cases

Returns a list of TestCases to be run in a TestLoader for basic 2d plots (scatter, bar, line, etc.).

Testcases are as follows: 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are as expected 2. BasicCase: Asserts data matches data_exp, and other assertions based on params listed below For more on tests, see init method above. For more on assertions, see the autograde package.

suite

Returns a Testsuite from cases to be run in a TestRunner

class matplotcheck.cases.PlotFoliumSuite(fmap, markers)[source]

Bases: object

A generic object to test Folium Maps.

Parameters:
  • fmap (folium map to be tested) –
  • markers (set of tuples where each tuple represents the x and y coord of) –
  • expected marker (an) –
cases

Returns a TestSuite for Folium Maps. Testcase are as follows: 1. FoliumCase: asserts map is of type folium.map and contains expected markers

suite

Returns a Testsuite from cases to be run in a TestRunner

class matplotcheck.cases.PlotHistogramSuite(ax, n_bins=None, xlims=None, ylims=None, title_contains=[], xlabel_contains=[], ylabel_contains=[])[source]

Bases: matplotcheck.cases.PlotBasicSuite

A PlotBasicSuite object to test a Matplotlib histogram plot. Since students have the flexibility to determine bin size, we are testing the set up of the histogram more than the data in the histogram itself.

Parameters:
  • ax (Matplotlib Axes to be tested) –
  • n_bins (tuple of ints. First int is the minimum number of bins containing) – negative values. Second int is the minimum number of bins containing positive values
  • xlims (tuple of 2 tuples. First tuple contains range the left x limit must) – be in, exclusive. Second tuple contains range the right x limit must be in, exclusive.
  • ylims (tuple of 2 tuples. First tuple contains range the bottom y limit) – must be in, exclusive. Second tuple contains range the top y limit must be in, exclusive.
  • title_contains (list of lower case strings where each string is expected to) – be in title, barring capitalization. If value is an empty list: test is just to see that title exists and is not an empty string If value is None: asserts no title
  • xlabel_contains (list of lower case strings where each string is expected) – to be in x-axis label, barring capitalization. If value is an empty list: test is just to see that x-axis label exists and is not an empty string If value is None: asserts no label is expressed
  • ylabel_contains (list of lower case strings where each string is expected) – to be in y-axis label, barring capitalization. If value is an empty list: test is just to see that y-axis label exists and is not an empty string If value is None: asserts no label is expressed
cases

Asserts the title, x-axis label, and y-axis label are as expected 2. HistogramCase: number of negative and positive bins as declares in n_bins. x axis limits and y axis limits are in range declared by xlims and y lims. For more on tests, see init method above. For more on assertions, see the autograde package.

Type:

Returns list of cases for a histogram. Testcases are as follows

Type:
  1. LabelsCase
class matplotcheck.cases.PlotRasterSuite(ax, im_expected, caption_strings, im_classified=True, legend_labels=None, title_type='either', title_contains=[], markers=None, markers_by_size=None, markers_groupby=None, lines=None, lines_groupby=None, polygons=None, colorbar_range=None)[source]

Bases: matplotcheck.cases.PlotVectorSuite

A PlotBasicSuite object to test a Matplotlib raster plot.

Parameters:
  • ax (Matplotlib Axes to be tested) –
  • im_expected (array containing values of an expected image) –
  • caption_strings (list of lists. Each internal list is a list of strings) –
  • at least one string must be (where) – found in the caption, barring capitalization if empty list: asserts caption exists and not an empty string if None: assertion is passed
  • im_classified (boolean if image on ax is classfied) –
  • legend_labels (list of lists. Each internal list represents a) –
  • category. (classification) – Said list is a list of strings where at least one string is expected to be in the legend label for this category. Internal lists must be in the same order as bins in im_expected.
  • title_type (one of the following strings ["figure", "axes", "either"],) –
  • which title to test (stating) –
  • title_contains (list of strings expected to be in title) –
  • markers (Geopandas dataframe with geometry column containing expected) –
  • objects (Point) –
  • markers_by_size (column title from markers_exp that points are expected) –
  • be sorted by (to) – if None, assertion is passed
  • markers_groupby (column title from markers_exp that points are expected) –
  • be grouped by/contain (to) – like attributes. Attributes tested are: marker type, markersize, and color if None, assertion is passed
  • lines (Geopandas dataframe with geometry column containing expected) –
  • and MultiLineString objects (LineString) –
  • lines_groupby (column title from line_exp that lines are expected to be) –
  • by/contain (grouped) – like attributes. Attributes tested are: line style, line width, and color if None, assertion is passed
  • polygons (list of lines where each line is a list of coord tuples for the) –
  • polygon (exterior) –
  • colorbar_range (tuple of (min, max) for colorbar.) – If empty tuple: asserts a colorbar exists, but does not check values If None: assertion is passed
cases

Returns a list of TestCases for spatial raster plots. Testcase are as follows: 1. CaptionCase: assert caption is in appropriate location with strings expressed in caption_strings 2. LabelsCase: asserts the title contains strings in title_contains, and x and y labels are empty 3. RasterCase: asserts raster image matches im_expected and legend is correct if image is classified 4. VectorCase: assert vector data is as expected

class matplotcheck.cases.PlotTimeSeriesSuite(ax, data_exp, xcol, ycol, no_data_val=None, major_locator_exp=None, minor_locator_exp=None, title_contains=[], xlabel_contains=[], ylabel_contains=[])[source]

Bases: matplotcheck.cases.PlotBasicSuite

A PlotBasicSuite object to test Matplotlib time series plots.

Parameters:
  • ax (Matplotlib Axes to be tested) –
  • data_exp (pandas dataframe containing plot data) –
  • x_col (string column title in data_exp that contains xaxis data) –
  • y_col (string column title in data_exp that contains yaxis data) –
  • no_data_val (float representing no data, as stated by the input data) –
  • major_locator_exp (one of the following ['decade', 'year', 'month',) –
  • 'day', None] ('week',) – decade: if tick should be shown every ten years year: if tick should be shown every new year month: if tick should be shown every new month week: if tick should be shown every new week day: if tick should be shown every new day
  • minor_locator_exp (one of the following ['decade', 'year', 'month',) –
  • 'day', None], as expressed above ('week',) –
  • title_contains (list of lower case strings where each string is expected) –
  • be in title, barring capitalization. (to) – If value is an empty list: test is just to see that title exists and is not an empty string If value is None: asserts no title
  • xlabel_contains (list of lower case strings where each string is expected) –
  • be in x-axis label, barring capitalization. (to) – If value is an empty list: test is just to see that x-axis label exists and is not an empty string If value is None: asserts no label is expressed
  • ylabel_contains (list of lower case strings where each string is expected) –
  • be in y-axis label, barring capitalization. (to) – If value is an empty list: test is just to see that y-axis label exists and is not an empty string If value is None: asserts no label is expressed
cases

Returns a list of TestCases for time series plots. Testcase are as follows: 1. LabelsCase: Asserts the title, x-axis label, and y-axis label are as expected 2. TickReformatCase: Asserts x-axis ticks have large ticks as express in major_locator_exp and small ticks as express in minor_locator_exp 3. TimeSeriesCase: Asserts data matches data_exp and is converted to time objects For more on tests, see init method above. For more on assertions, see the autograde package.

class matplotcheck.cases.PlotVectorSuite(ax, caption_strings, legend_labels, title_type='either', title_contains=[], markers=None, lines=None, polygons=None, markers_groupby=None, lines_groupby=None, markers_by_size=None)[source]

Bases: matplotcheck.cases.PlotBasicSuite

A PlotBasicSuite object to test a Matplotlib plot with spatial vector data.

Parameters:
  • ax (Matplotlib Axes to be tested) –
  • caption_strings (list of lists. Each internal list is a list of lower) –
  • strings where at least one string must be (case) – found in the caption, barring capitalization if None: assert caption does not exist if empty list: asserts caption exists and not an empty string
  • legend_labels (list of lower case stings. Each string is an expected) –
  • label in the legend. (entry) –
  • title_type (one of the following strings ["figure", "axes", "either"]) – “figure”: only the figure title (suptitle) will be tested “axes”: only the axes title (suptitle) will be tested “either”: either the figure title or axes title will pass this assertion. The combined title will be tested.
  • title_contains (list of lower case strings where each string is expected) –
  • be in title, barring capitalization. (to) – If value is an empty list: test is just to see that title exists and is not an empty string If value is None: asserts no title
  • markers (Geopandas dataframe with geometry column containing expected) –
  • objects (Point) –
  • lines (Geopandas dataframe with geometry column containing expected) –
  • and MultiLineString objects (LineString) –
  • polygons (list of lines where each line is a list of coord tuples for the) –
  • polygon (exterior) –
  • markers_groupby (column title from markers_exp that points are expected) –
  • be grouped by/contain (to) – like attributes. Attributes tested are: marker type, markersize, and color if None, assertion is passed
  • lines_groupby (column title from line_exp that lines are expected to be) –
  • by/contain (grouped) – like attributes. Attributes tested are: line style, line width, and color if None, assertion is passed
  • markers_by_size (column title from markers_exp that points are expected) –
  • be sorted by (to) – if None, assertion is passed
cases

Returns a list of TestCases for spatial vector plots. Testcase are as follows: 1. CaptionCase: assert caption is in appropriate location with strings expressed in caption_contains 2. LabelsCase: asserts the title contains strings in title_contains, and x and y labels are empty 3. LegendCase: assert legend(s) is/are in appropriate location with legend_labels 4. VectorCase: assert vector data is as expected in markers, lines, and polygons For more on tests, see init method above. For more on assertions, see the autograde package.

matplotcheck.cases.loadTests(tests)[source]

matplotcheck.folium module

class matplotcheck.folium.FoliumTester(fmap)[source]

Bases: object

Object to test Folium plots

Parameters:map (folium.folium.Map object) –
assert_folium_marker_locs(markers, m='Markers not shown in appropriate location')[source]

Asserts folium contains markers with locations described in markers_exp and only those markers, with error message m

Parameters:
  • markers (tuples) – Set of tuples where each tuple represents the x and y coord of an expected marker.
  • m (string) – Error message if assertion is not met.
assert_map_type_folium()[source]

Asserts fmap is of type folium.folium.Map

matplotcheck.notebook module

matplotcheck.notebook.convert_axes(plt, which_axes='current')[source]

Saves current working plot and axes as variables for testing purposes. Axes that is/are saved is denoted by which_axes.

Parameters:
  • plt (matplotlib plot) – Matplotlib plot to be tested.
  • which_axes (string) – String from the following list [‘current’, ‘last’, ‘first’, ‘all’] stating which axes we are saving for testing.
Returns:

ax – Matplotlib axes or list of axes as express by which_axes

Return type:

Matplotlib axes or list

matplotcheck.notebook.error_test(n, n_exp)[source]

Tests the number of cells that produced an error.

Parameters:
  • n (int) – Number of cells that that did not produce an error.
  • n_exp (int) – Number of cell that are checked if producing an error.
Returns:

Return type:

print statement of test results

matplotcheck.notebook.import_test(var_dict, n)[source]

Tests no import statements are found after the first cell in a Jupyter Notebook

Parameters:
  • vars_dict (dictionary) – Dictionary produced by ‘locals()’ in notebook.
  • n (int) – number of cells to be tested for import statement in Jupyter Notebook
Returns:

Return type:

print statement of test results

matplotcheck.notebook.remove_comments(input_string)[source]

Helper function for import_test. Removes all parts of string that would be commented out by # in python

Parameters:input_string (string) – String to be modified.
Returns:Sting where all parts commented out by a ‘#’ are removed from input_string.
Return type:string

matplotcheck.raster module

class matplotcheck.raster.RasterTester(ax)[source]

Bases: matplotcheck.vector.VectorTester

A PlotTester for spatial raster plots.

Parameters:ax (`matplotlib.axes.Axes` object) –
assert_colorbar_range(crange)[source]

Asserts colorbar range matches min and max of crange parameter.

Parameters:crange (tuple of (min, max) for colorbar) – If given empty tuple, asserts exactly 1 colorbar exists, but does not check values.
Returns:
Return type:Nothing (if checks pass) or raises error
assert_image(im_expected, im_classified=False, m='Incorrect Image Displayed')[source]

Asserts the first image in Axes ax matches array im_expected

Parameters:
  • im_expected (Numpy Array) – Array containing the expected image data.
  • im_classified (boolean) – Set to True image has been classified. Since classified images values can be reversed or shifted and still produce the same image, setting this to True will allow those changes.
  • m (string) – String error message if assertion is not met.
Returns:

Return type:

Nothing (if checks pass) or raises error

assert_image_full_screen(m='Image is stretched inaccurately')[source]

Asserts the first image in ax fills the entire axes window

Parameters:m (error message if assertion is not met) –
Returns:
Return type:Nothing (if checks pass) or raises error with message m
assert_legend_accuracy_classified_image(im_expected, all_label_options)[source]

Asserts legend correctly describes classified image on Axes ax, checking the legend labels and the values

Parameters:
  • im_expected (array of arrays with expected classified image on ax.) – Class values must start with 0, 1, 2, etc.
  • all_label_options (list of lists) – Each internal list represents a class and said list is a list of strings where at least one string is expected to be in the legend label for this category. Internal lists must be in the same order as bins in im_expected, e.g. first internal list has the expected label options for class 0.
Returns:

Return type:

Nothing (if checks pass) or raises error

Notes

First compares all_label_options against the legend labels to find which element of all_label_options matches that entry. E.g. if the first legend entry has a match in the first list in all_label_options, then that legend entry corresponds to the first class (value 0). Then the plot image array is copied and the values are set to the legend label that match the values (i.e. the element in all_label_options). The same is done for the expected image array. Finally those two arrays of strings are compared. Passes if they match.

get_colorbars()[source]

Retrieve list of colorbars on axes ax

Returns:If no colorbars exist, Returns an empty list.
Return type:list of matplotlib.colorbar.Colorbar objects on axes.
get_plot_image()[source]

Returns images stored on the Axes object as a list of numpy arrays.

Returns:im_data – Numpy array of images stored on Axes object.
Return type:List

matplotcheck.timeseries module

class matplotcheck.timeseries.TimeSeriesTester(ax)[source]

Bases: matplotcheck.base.PlotTester

A PlotTester for 2 dimensional time series plots.

Parameters:ax (`matplotlib.axes.Axes` object) – The plot to be tested.
assert_no_data_value(nodata=999.99)[source]

Asserts nodata values have been removed from the data, when x is a datetime with error message m

Parameters:
  • nodata (float or int) – a nodata value that will be searched for in dataset
  • xtime (boolean) – does the x-axis contains datetime values?
assert_xdata_date(x_exp, m='X-axis is not in appropriate date format')[source]

Asserts x-axis data has been parsed into datetime objects. Matplotlib changes datetime to floats representing number of days since day 0. If you are using dates prior to year 270, this assertion will fail.

Parameters:x_exp (expected x_axis values, must be in a datetime format) –
assert_xticks_locs(tick_size='large', loc_exp=None, m='Incorrect X axis tick locations')[source]

Asserts that Axes ax has xaxis ticks as noted by tick_size and loc_exp

Parameters:
  • tick_size (str, opts: ['large','small']) – ‘large’: if testing large ticks ‘small’: if testing small ticks
  • loc_exp (string ['decade','year', 'month', 'week', 'day']) – ‘decade’: if tick should be shown every ten years ‘year’: if tick should be shown every new year ‘month’: if tick should be shown every new month ‘week’: if tick should be shown every new week ‘day’: if tick should be shown every new day None: if no tick location has been specified. This will automatically assert True
  • m (error message if assertion is not met) –
assert_xticks_reformatted(tick_size='large', loc_exp=None, m='x ticks have not been reformatted properly')[source]

Asserts that Axes ax xtick have been reformatted as denoted by tick_size and loc_exp, with error message m

Parameters:
  • tick_size (must be one of the following ['large','small']) – ‘large’: if testing large ticks ‘small’: if testing small ticks
  • loc_exp (string ['decade','year', 'month', 'week', 'day']) – ‘decade’: if tick should be shown every ten years ‘year’: if tick should be shown every new year ‘month’: if tick should be shown every new month ‘week’: if tick should be shown every new week ‘day’: if tick should be shown every new day None: if no tick format has been specified. This will automatically assert True
  • m (string) – string error message if assertion is not met

matplotcheck.vector module

class matplotcheck.vector.VectorTester(ax)[source]

Bases: matplotcheck.base.PlotTester

A PlotTester for spatial vector plots.

Parameters:ax (`matplotlib.axes.Axes` object) –
assert_collection_sorted_by_markersize(df_expected, sort_column)[source]

Asserts a collection of points vary in size by column expressed in sort_column

Parameters:
  • df_expected (geopandas dataframe with geometry column of expected point) –
  • locations
  • sort_column (column title from df_expected that points are expected to) –
  • sorted by (be) – if None, assertion is passed
assert_lines(lines_expected, m='Incorrect Line Data')[source]

Asserts the line data in Axes ax is equal to lines_expected with error message m. If line_expected is None or an empty list, assertion is passed

Parameters:
  • lines_expected (Geopandas Dataframe with a geometry column consisting) –
  • MultilineString and LineString objects (of) –
  • m (string error message if assertion is not met) –
assert_lines_grouped_by_type(lines_expected, sort_column, m='Line attributes not accurate by type')[source]

Asserts that the lines on Axes ax display like attributes based on their type with error message m attributes tested are: color, linewidth, linestyle

Parameters:
  • lines_expected (Geopandas Dataframe with geometry column consisting of) –
  • and LineString objects (MultiLineString) –
  • sort_column (string of column title in lines_expected that contains) –
  • lines are expected to be grouped by (types) –
  • m (string error message if assertion is not met) –
assert_points(points_expected, m='Incorrect Point Data')[source]

Asserts the point data in Axes ax is equal to points_expected data with error message m. If points_expected not a GeoDataFrame, test fails.

Parameters:
  • points_expected (GeoDataFrame) –
  • with the expected points for the axis. (GeoDataFrame) –
  • m (string (default = "Incorrect Point Data")) –
  • error message if assertion is not met. (String) –
assert_points_grouped_by_type(data_exp, sort_column, m='Point attributes not accurate by type')[source]

Asserts that the points on Axes ax display attributes based on their type with error message m attributes tested are: color, marker, and markersize

Parameters:
  • data_exp (Geopandas Dataframe with Point objects in column 'geometry') – an additional column with title sort_column, denotes a category for each point
  • sort_column (string of column label in dataframe data_exp.) – this column contains values expressing which points belong to which group
  • m (string error message if assertion is not met) –
assert_polygons(polygons_expected, dec=None, m='Incorrect Polygon Data')[source]

Asserts the polygon data in Axes ax is equal to polygons_expected to decimal place dec with error message m If polygons_expected is am empty list or None, assertion is passed.

Parameters:
  • polygons_expected (List or GeoDataFrame) – List of polygons expected to be founds on Axes ax or a GeoDataFrame containing the expected polygons.
  • dec (int (Optional)) – Int stating the desired decimal precision. If None, polygons must be exact.
  • m (string (default = "Incorrect Polygon Data")) – String error message if assertion is not met.
get_lines()[source]

Returns a dataframe with all lines on ax

Returns:
  • output (DataFrame with column ‘lines’. Each row represents one line)
  • segment. Its value in ‘lines’ is a list of tuples representing the
  • line segment.
get_lines_by_attributes()[source]

Returns a sorted list of lists where each list contains line segments of the same attributes: color, linewidth, and linestyle

Returns:
  • sorted list where each list represents all lines with the same
  • attributes
get_lines_by_collection()[source]

Returns a sorted list of list where each list contains line segments from the same collections

Returns:
  • sorted list where each list represents all lines from the same
  • collection
get_points()[source]

Returns a Pandas dataframe with all x, y values for points on axis.

Returns:
  • output (DataFrame with columns ‘x’ and ‘y’. Each row represents one)
  • points coordinates.
get_points_by_attributes()[source]

Returns a sorted list of lists where each list contains tuples of xycoords for points of the same attributes: color, marker, and markersize

Returns:
  • sorted list where each list represents all points with the same color.
  • each point is represented by a tuple with its coordinates.
get_polygons()[source]

Returns all polygons on Axes ax as a sorted list of polygons where each polygon is a list of coord tuples

Returns:
  • output (sorted list of polygons. Each polygon is a list tuples. Each)
  • tuple is a coordinate.
sort_collection_by_markersize()[source]

Returns a pandas dataframe of points in collections on Axes ax.

Returns:
  • pandas dataframe with columns x, y, point_size. Each row reprsents a
  • point on Axes ax with location x,y and markersize pointsize

Module contents

Autograde functions for the earthlab class.