-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.qmd
469 lines (366 loc) · 13.3 KB
/
index.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
---
site-url: https://saforem2.github.io/ambivalent
# editor:
# render-on-save: true
execute:
freeze: auto
format:
html: default
# revealjs:
# output-file: slides.html
gfm:
default-image-extension: svg
author: Sam Foreman
output-file: "README.md"
---
[~~`opinionated`~~](https://github.com/saforem2/opinionated) $\longrightarrow$ [**`ambivalent`**](https://github.com/saforem2/ambivalent) 🤷🏻
Clean, simple style for Matplotlib figures.
Transparent backgrounds with grey text $\textcolor{#838383}{\blacksquare}$ that
are accessible / legible and `{light, dark}`-mode independent.
## Install
```bash
python3 -m pip install ambivalent
```
## Getting Started
```{python}
#| echo: false
#| output: false
# automatically detect and reload local changes to modules
%load_ext autoreload
%autoreload 2
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
import matplotlib_inline
matplotlib_inline.backend_inline.set_matplotlib_formats('svg', 'retina')
```
<!-- - Use `ambivalend.STYLES['ambivalent']` as the default style for `matplotlib`. -->
```{python}
#| code-fold: false
#| echo: true
import ambivalent
import matplotlib.pyplot as plt
plt.style.use(ambivalent.STYLES['ambivalent'])
```
## Examples
### `seaborn` Tips Dataset
- [Seaborn Gallery](https://seaborn.pydata.org/examples/index.html)
- [Tips Dataset Example](https://seaborn.pydata.org/generated/seaborn.kdeplot.html)
<!-- <details closed><summary><code>code</code>:</summary> -->
```{python}
#| code-fold: true
#| label: fig-py-tips-density
#| output: true
#| fig-cap: "Tips -- Density Plot"
#| layout: [[100]]
import seaborn as sns
tips = sns.load_dataset("tips")
tips.head()
fig, ax = plt.subplots(figsize=(6, 6)) # , ncols=2)
_ = sns.kdeplot(
data=tips, x="total_bill", hue="size",
fill=True, common_norm=False, palette="flare_r",
alpha=.3, linewidth=0,
ax=ax, # [0],
)
_ = ax.set_ylabel('')
plt.show()
```
<!-- </details> -->
### `seaborn` Scatter Plot
<!-- <details closed><summary><code>code</code>:</summary> -->
```{python}
#| code-fold: true
#| label: fig-py-diamonds-scatter
#| output: asis
#| fig-cap: "scatter plot with markers of varying size and color"
#| layout: [[100]]
import seaborn as sns
import matplotlib.pyplot as plt
# Load the example diamonds dataset
diamonds = sns.load_dataset("diamonds")
# Draw a scatter plot while assigning point colors and sizes to different
# variables in the dataset
f, ax = plt.subplots(figsize=(6, 6))
_ = sns.despine(f, left=True, bottom=True)
_ = clarity_ranking = ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"]
_ = sns.scatterplot(x="carat", y="price",
hue="clarity", size="depth",
palette="flare",
hue_order=clarity_ranking,
sizes=(1, 8), linewidth=0,
data=diamonds, ax=ax)
```
<!-- </details> -->
### Histogram + Scatter Plot
<!-- <details closed><summary><code>code</code>:</summary> -->
```{python}
#| code-fold: true
#| label: fig-py-hist-scatter
#| output: true
#| fig-cap: "Combo histogram + Scatter Plot with Density Contours"
#| layout: [[100]]
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Simulate data from a bivariate Gaussian
n = 10000
mean = [0, 0]
cov = [(2, .4), (.4, .2)]
rng = np.random.RandomState(0)
x, y = rng.multivariate_normal(mean, cov, n).T
# Draw a combo histogram and scatterplot with density contours
f, ax = plt.subplots(figsize=(6, 6))
_ = sns.scatterplot(x=x, y=y, s=5, color="#666666", alpha=0.3)
_ = sns.histplot(x=x, y=y, bins=50, pthresh=.1, cmap="flare_r")
_ = sns.kdeplot(x=x, y=y, levels=5, color="w", linewidths=1)
_ = ax.set_xlabel('x')
_ = ax.set_ylabel('y')
_ = plt.show()
```
<!-- </details> -->
### Jointplot
<!-- <details closed><summary><code>code</code>:</summary> -->
```{python}
#| code-fold: true
#| label: fig-py-kde-2d
#| output: true
#| fig-cap: "Joint Distribution with Kernel Density Estimation"
#| layout: [[100]]
import seaborn as sns
# Load the penguins dataset
penguins = sns.load_dataset("penguins")
# Show the joint distribution using kernel density estimation
import matplotlib as mpl
with mpl.rc_context(plt.rcParams.update({'axes.grid': False})):
g = sns.jointplot(
data=penguins,
x="bill_length_mm",
y="bill_depth_mm",
hue="species",
edgecolors='none',
alpha=0.4,
)
_ = plt.grid(False)
plt.show()
```
<!-- </details> -->
### Matplotlib Histograms
<!-- <details closed><summary><code>code</code>:</summary> -->
```{python}
#| code-fold: true
#| label: fig-py-mpl-hists
#| output: true
#| fig-cap: "Histograms with Matplotlib"
#| layout: [[100]]
import matplotlib.pyplot as plt
import numpy as np
n_bins = 10
x = np.random.randn(1000, 3)
plt.rcParams['axes.grid'] = True
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(nrows=2, ncols=2)
colors = ['#333333', '#666666', '#999999']
ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors)
_ = ax0.legend()
_ = ax0.set_title('bars with legend')
_ = ax1.hist(x, n_bins, density=True, histtype='bar', stacked=True, alpha=0.4)
_ = ax1.set_title('stacked bar')
_ = ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
_ = ax2.set_title('stack step (unfilled)')
# Make a multiple-histogram of data-sets with different length.
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
_ = ax3.hist(x_multi, n_bins, histtype='bar')
_ = ax3.set_title('different sample sizes')
_ = fig.tight_layout()
plt.show()
```
<!-- </details> -->
## Gallery[^examples]
<details closed><summary><italic>More Examples...</italic></summary>
[^examples]: Examples from [Matplotlib Examples](https://matplotlib.org/stable/gallery/index.html)
<!-- ::: {#fig-gallery style="display: flex; flex-direction:row; align-items: flex-end"} -->
::: {layout-nrow=3}
::: {layout-ncol=2}
](./assets/penguins.svg){#fig-penguins .stretch}
](./assets/spectrum.svg){#fig-spectrum .stretch}
:::
<!-- ::: {layout="[[45, 45]]" layout-valign="bottom" style="text-align:center;"} -->
::: {layout-ncol=2}
{#fig-tips-kde .stretch}
{#fig-2d-kde .stretch}
:::
<!-- ::: {layout="[[80]]" style="display: flex; text-align:center;"} -->
::: {layout-ncol=1}
{#fig-mpl-hist .stretch}
:::
:::
<!-- ::: {.stretch layout="[[31, 31, 31]]" layout-valign="bottom" style="display: flex; text-align:center!important;"} -->
::: {#fig-chains-J layout-ncol=3}
{.stretch}
{.stretch}
{.stretch}
$|J|$ during training
:::
::: {#fig-chains-dQ layout="[[80]]" layout-valign="bottom" style="display: flex; text-align:center;"}
{#fig-chains .stretch}
Figure from [`l2hmc-qcd` Notebook](https://saforem2.github.io/l2hmc-qcd/qmd/l2hmc-2dU1/l2hmc-2dU1.html#inference)
:::
::: {#fig-xeps style="display: flex; text-align:center;"}
{.stretch}
$\varepsilon_{x}$ during training
:::
::: {#fig-veps style="display: flex; text-align:center;"}
{.stretch}
$\varepsilon_{x}$ during training
:::
::: {#fig-combined-chains layout="[[80]]" style="display: flex; text-align:center;"}
{#fig-dQhist .stretch}
Figure from [`l2hmc-qcd` Notebook](https://saforem2.github.io/l2hmc-qcd/qmd/l2hmc-2dU1/l2hmc-2dU1.html)
:::
</details>
<!-- ```{python} -->
<!-- #| code-fold: true -->
<!-- #| code-summary: "boxenplot" -->
<!-- #| label: fig-py-boxenplot -->
<!-- #| output: true -->
<!-- #| fig-cap: "Seaborn Boxenplot" -->
<!-- #| layout: [[100]] -->
<!---->
<!-- import seaborn as sns -->
<!---->
<!-- diamonds = sns.load_dataset("diamonds") -->
<!-- clarity_ranking = ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"] -->
<!---->
<!-- sns.boxenplot( -->
<!-- diamonds, x="clarity", y="carat", -->
<!-- color="b", order=clarity_ranking, width_method="linear", -->
<!-- ) -->
<!-- ``` -->
<!-- ```{python} -->
<!-- import warnings -->
<!-- from ambivalent import STYLES -->
<!-- import matplotlib.pyplot as plt -->
<!-- import numpy as np -->
<!---->
<!-- plt.style.use(STYLES['ambivalent']) -->
<!---->
<!-- # some random data -->
<!-- x = np.random.randn(1000) -->
<!-- y = np.random.randn(1000) -->
<!---->
<!---->
<!-- def scatter_hist(x, y, ax, ax_histx, ax_histy, alpha: float = 0.4): -->
<!-- # no labels -->
<!-- ax_histx.tick_params(axis="x", labelbottom=False) -->
<!-- ax_histy.tick_params(axis="y", labelleft=False) -->
<!---->
<!-- # the scatter plot: -->
<!-- ax.scatter(x, y, alpha=alpha) -->
<!---->
<!-- # now determine nice limits by hand: -->
<!-- binwidth = 0.25 -->
<!-- xymax = max(np.max(np.abs(x)), np.max(np.abs(y))) -->
<!-- lim = (int(xymax/binwidth) + 1) * binwidth -->
<!---->
<!-- bins = np.arange(-lim, lim + binwidth, binwidth) -->
<!-- ax_histx.hist(x, bins=bins) -->
<!-- ax_histy.hist(y, bins=bins, orientation='horizontal') -->
<!-- ``` -->
<!-- ### 2D Density -->
<!---->
<!-- ```{python} -->
<!-- #| code-fold: true -->
<!-- #| code-summary: "Make the plot" -->
<!-- #| label: fig-py-density2d -->
<!-- #| output: true -->
<!-- #| fig-cap: "2D Density plot" -->
<!-- #| layout: [[100]] -->
<!---->
<!-- # Start with a square Figure. -->
<!-- fig = plt.figure(figsize=(6, 6)) -->
<!-- # Add a gridspec with two rows and two columns and a ratio of 1 to 4 between -->
<!-- # the size of the marginal axes and the main axes in both directions. -->
<!-- # Also adjust the subplot parameters for a square plot. -->
<!-- gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4), -->
<!-- left=0.1, right=0.9, bottom=0.1, top=0.9, -->
<!-- wspace=0.15, hspace=0.15) -->
<!-- # Create the Axes. -->
<!-- ax = fig.add_subplot(gs[1, 0]) -->
<!-- ax_histx = fig.add_subplot(gs[0, 0], sharex=ax) -->
<!-- ax_histy = fig.add_subplot(gs[1, 1], sharey=ax) -->
<!-- _ = fig.axes[1].grid(False) -->
<!-- _ = fig.axes[2].set_xticklabels([]) -->
<!-- _ = fig.axes[1].set_yticklabels([]) -->
<!-- _ = fig.axes[2].grid(False) -->
<!-- _ = fig.axes[0].set_xticklabels(fig.axes[0].get_xticklabels()) -->
<!-- _ = fig.axes[0].set_yticklabels(fig.axes[0].get_yticklabels()) -->
<!---->
<!-- # Draw the scatter plot and marginals. -->
<!-- _ = scatter_hist(x, y, ax, ax_histx, ax_histy) -->
<!-- _ = plt.show() -->
<!-- ``` -->
<!---->
<!---->
<!-- ```{python} -->
<!-- import numpy as np -->
<!-- import matplotlib.animation as animation -->
<!---->
<!-- # Fixing random state for reproducibility -->
<!-- np.random.seed(19680801) -->
<!---->
<!---->
<!-- def random_walk(num_steps, max_step=0.05): -->
<!-- """Return a 3D random walk as (num_steps, 3) array.""" -->
<!-- start_pos = np.random.random(3) -->
<!-- steps = np.random.uniform(-max_step, max_step, size=(num_steps, 3)) -->
<!-- walk = start_pos + np.cumsum(steps, axis=0) -->
<!-- return walk -->
<!---->
<!---->
<!-- def update_lines(num, walks, lines): -->
<!-- for line, walk in zip(lines, walks): -->
<!-- # NOTE: there is no .set_data() for 3 dim data... -->
<!-- line.set_data(walk[:num, :2].T) -->
<!-- line.set_3d_properties(walk[:num, 2]) -->
<!-- return lines -->
<!---->
<!---->
<!-- # Data: 40 random walks as (num_steps, 3) arrays -->
<!-- num_steps = 30 -->
<!-- walks = [random_walk(num_steps) for index in range(40)] -->
<!---->
<!-- # Attaching 3D axis to the figure -->
<!-- fig = plt.figure() -->
<!-- ax = fig.add_subplot(projection="3d") -->
<!---->
<!-- # Create lines initially without data -->
<!-- lines = [ax.plot([], [], [])[0] for _ in walks] -->
<!---->
<!-- # Setting the axes properties -->
<!-- _ = ax.set(xlim3d=(0, 1), xlabel='X') -->
<!-- _ = ax.set(ylim3d=(0, 1), ylabel='Y') -->
<!-- _ = ax.set(zlim3d=(0, 1), zlabel='Z') -->
<!---->
<!-- # Creating the Animation object -->
<!-- ani = animation.FuncAnimation( -->
<!-- fig, update_lines, num_steps, fargs=(walks, lines), interval=100) -->
<!---->
<!-- plt.show() -->
<!-- ``` -->
::: {.callout-tip icon=false title='[💝 Status]{.dim-text}' collapse="false" style="text-align: left!important; width:100%; border: none!important; border-left: 1px solid var(--dim-text)!important; border-radius: 0pt!important; background-color: var(--bg-transparent); opacity:100%;"}
[]{style="text-align:center;"}
```{python}
#| echo: false
import datetime
from rich import print
now = datetime.datetime.now()
day = now.strftime('%m/%d/%Y')
time = now.strftime('%H:%M:%S')
print(' '.join([
"[dim italic]Last Updated[/]:",
f"[#F06292]{day}[/]",
f"[dim]@[/]",
f"[#1A8FFF]{time}[/]"
]))
```
:::