Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132930 views
License: OTHER
1
import matplotlib
2
import numpy as np
3
from numpy.testing import assert_array_equal, assert_allclose
4
5
6
def get_data(ax):
7
lines = ax.get_lines()
8
if len(lines) > 0:
9
xydata = np.concatenate(
10
[x.get_xydata() for x in lines], axis=0)
11
12
else:
13
collections = ax.collections
14
if len(collections) > 0:
15
xydata = np.concatenate(
16
[x.get_offsets() for x in collections], axis=0)
17
18
else:
19
raise ValueError("no data found")
20
21
return xydata
22
23
24
def get_label_text(ax):
25
text = [x for x in ax.get_children()
26
if isinstance(x, matplotlib.text.Text)]
27
text = [x for x in text if x.get_text() != ax.get_title()]
28
text = [x for x in text if x.get_text().strip() != '']
29
return [x.get_text().strip() for x in text]
30
31
32
def get_label_pos(ax):
33
text = [x for x in ax.get_children()
34
if isinstance(x, matplotlib.text.Text)]
35
text = [x for x in text if x.get_text() != ax.get_title()]
36
text = [x for x in text if x.get_text().strip() != '']
37
return np.vstack([x.get_position() for x in text])
38
39
40
def get_image(ax):
41
images = ax.get_images()
42
if len(images) == 0:
43
raise ValueError("Expected one image, but there were none. Did you remember to call the plotting function (probably `matshow` or `imshow`)?")
44
if len(images) > 1:
45
raise ValueError("Expected one image, but there were {}. Did you call the plotting function (probably `matshow` or `imshow`) more than once?".format(len(images)))
46
return images[0]
47
48
49
def get_imshow_data(ax):
50
image = get_image(ax)
51
return image._A
52
53
def get_image_colormap(ax):
54
image = get_image(ax)
55
return image.cmap.name
56
57
def assert_image_equal(ax, arr):
58
data = get_imshow_data(ax)
59
assert_array_equal(data, arr)
60
61
62
def assert_image_allclose(ax, arr):
63
data = get_imshow_data(ax)
64
assert_allclose(data, arr, atol=1e-6)
65
66