Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
1
import pandas as pd
2
import numpy as np
3
import matplotlib.pyplot as plt
4
import seaborn as sns
5
6
import matplotlib as mpl
7
mpl.rcParams['lines.linewidth'] = 2.0
8
9
10
def three_frame(world, n_seq, seed=17):
11
"""Draw three timesteps.
12
13
world: object with step, loop, and draw
14
n_seq: 3-tuple, number of steps before each draw
15
seed: random see for NumPy
16
"""
17
np.random.seed(seed)
18
plt.figure(figsize=(10, 4))
19
20
for i, n in enumerate(n_seq):
21
plt.subplot(1, 3, i+1)
22
world.loop(n)
23
world.draw()
24
25
plt.tight_layout()
26
27
28
def savefig(filename, **options):
29
"""Save the current figure.
30
31
Keyword arguments are passed along to plt.savefig
32
33
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html
34
35
filename: string
36
"""
37
print("Saving figure to file", filename)
38
plt.savefig(filename, **options)
39
40
41
def underride(d, **options):
42
"""Add key-value pairs to d only if key is not in d.
43
44
d: dictionary
45
options: keyword args to add to d
46
"""
47
for key, val in options.items():
48
d.setdefault(key, val)
49
50
return d
51
52
53
def decorate(**options):
54
"""Decorate the current axes.
55
56
Call decorate with keyword arguments like
57
58
decorate(title='Title',
59
xlabel='x',
60
ylabel='y')
61
62
The keyword arguments can be any of the axis properties
63
64
https://matplotlib.org/api/axes_api.html
65
66
In addition, you can use `legend=False` to suppress the legend.
67
68
And you can use `loc` to indicate the location of the legend
69
(the default value is 'best')
70
"""
71
loc = options.pop("loc", "best")
72
if options.pop("legend", True):
73
legend(loc=loc)
74
75
plt.gca().set(**options)
76
plt.tight_layout()
77
78
79
def legend(**options):
80
"""Draws a legend only if there is at least one labeled item.
81
82
options are passed to plt.legend()
83
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
84
85
"""
86
underride(options, loc="best", frameon=False)
87
88
ax = plt.gca()
89
handles, labels = ax.get_legend_handles_labels()
90
if handles:
91
ax.legend(handles, labels, **options)
92
93
94
def set_palette(*args, **kwds):
95
"""Set the matplotlib color cycler.
96
97
args, kwds: same as for sns.color_palette
98
99
Also takes a boolean kwd, `reverse`, to indicate
100
whether the order of the palette should be reversed.
101
102
returns: list of colors
103
"""
104
reverse = kwds.pop('reverse', False)
105
palette = sns.color_palette(*args, **kwds)
106
107
palette = list(palette)
108
if reverse:
109
palette.reverse()
110
111
cycler = plt.cycler(color=palette)
112
plt.gca().set_prop_cycle(cycler)
113
return palette
114
115
116
117