📚 The CoCalc Library - books, templates and other resources
License: OTHER
import matplotlib1import numpy as np2from numpy.testing import assert_array_equal, assert_allclose345def get_data(ax):6lines = ax.get_lines()7if len(lines) > 0:8xydata = np.concatenate(9[x.get_xydata() for x in lines], axis=0)1011else:12collections = ax.collections13if len(collections) > 0:14xydata = np.concatenate(15[x.get_offsets() for x in collections], axis=0)1617else:18raise ValueError("no data found")1920return xydata212223def get_label_text(ax):24text = [x for x in ax.get_children()25if isinstance(x, matplotlib.text.Text)]26text = [x for x in text if x.get_text() != ax.get_title()]27text = [x for x in text if x.get_text().strip() != '']28return [x.get_text().strip() for x in text]293031def get_label_pos(ax):32text = [x for x in ax.get_children()33if isinstance(x, matplotlib.text.Text)]34text = [x for x in text if x.get_text() != ax.get_title()]35text = [x for x in text if x.get_text().strip() != '']36return np.vstack([x.get_position() for x in text])373839def get_image(ax):40images = ax.get_images()41if len(images) == 0:42raise ValueError("Expected one image, but there were none. Did you remember to call the plotting function (probably `matshow` or `imshow`)?")43if len(images) > 1:44raise ValueError("Expected one image, but there were {}. Did you call the plotting function (probably `matshow` or `imshow`) more than once?".format(len(images)))45return images[0]464748def get_imshow_data(ax):49image = get_image(ax)50return image._A5152def get_image_colormap(ax):53image = get_image(ax)54return image.cmap.name5556def assert_image_equal(ax, arr):57data = get_imshow_data(ax)58assert_array_equal(data, arr)596061def assert_image_allclose(ax, arr):62data = get_imshow_data(ax)63assert_allclose(data, arr, atol=1e-6)646566