Skip to content

Commit cc58dca

Browse files
author
Jahn, Kalle L
committed
minor edits and changes to matplotlib
1 parent fde6794 commit cc58dca

1 file changed

Lines changed: 80 additions & 40 deletions

File tree

notebooks/part0_python_intro/06_matplotlib.ipynb

Lines changed: 80 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,33 @@
192192
" ax.set_title(\"title\");"
193193
]
194194
},
195+
{
196+
"cell_type": "markdown",
197+
"metadata": {},
198+
"source": [
199+
"For complex subplots on a non-uniform grid, use `subplot_mosaic`: https://matplotlib.org/stable/users/explain/axes/mosaic.html#mosaic"
200+
]
201+
},
202+
{
203+
"cell_type": "code",
204+
"execution_count": null,
205+
"metadata": {},
206+
"outputs": [],
207+
"source": [
208+
"fig, axes = plt.subplot_mosaic(\n",
209+
" \"\"\"\n",
210+
" A.D\n",
211+
" CBD\n",
212+
" \"\"\"\n",
213+
" )# There is no internal meaning to the letters used, they could be anything.\n",
214+
"# `axes`` now is a dictionary with the letters as keys, Axes objects as values.\n",
215+
"for i, ax in axes.items():\n",
216+
" ax.plot(x, y, \"r\")\n",
217+
" ax.set_xlabel(\"x\")\n",
218+
" ax.set_ylabel(\"y\")\n",
219+
" ax.set_title(i);\n"
220+
]
221+
},
195222
{
196223
"cell_type": "markdown",
197224
"metadata": {},
@@ -249,7 +276,7 @@
249276
"source": [
250277
"The advantage with this method is that if curves are added or removed from the figure, the legend is automatically updated accordingly.\n",
251278
"\n",
252-
"The `legend` function takes an optional keyword argument `loc` that can be used to specify where in the figure the legend is to be drawn. The allowed values of `loc` are keywords for the various places the legend can be drawn. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html#matplotlib.axes.Axes.legend for details. Some of the most common `loc` values are:\n",
279+
"The `legend` function takes an optional keyword argument `loc` that can be used to specify where in the figure the legend is to be drawn. The allowed values of `loc` are keywords for the various places the legend can be drawn. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html#matplotlib.axes.Axes.legend for details. Some common `loc` values are:\n",
253280
"\n",
254281
"```python\n",
255282
"ax.legend(loc='best')\n",
@@ -285,7 +312,9 @@
285312
"cell_type": "markdown",
286313
"metadata": {},
287314
"source": [
288-
"Colors can also be defined by their names or RGB hex codes and optionally provide an alpha value using the `color` and `alpha` keyword arguments:"
315+
"Colors can also be defined by their names or RGB hex codes and optionally provide an alpha value using the `color` and `alpha` keyword arguments.\n",
316+
"\n",
317+
"There is also a [large list of named colors](https://matplotlib.org/stable/gallery/color/named_colors.html) available."
289318
]
290319
},
291320
{
@@ -449,7 +478,7 @@
449478
"\n",
450479
"That was easy, but it isn't so pretty with overlapping figure axes and labels, right?\n",
451480
"\n",
452-
"Overlapping figures can be dealt with using the `fig.tight_layout` method, which automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content:"
481+
"Overlapping figures can be dealt with by passing `layout=\"constrained\"` keyword argument when creating a `fig` object. The `constrained` layout automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content. See https://matplotlib.org/stable/users/explain/axes/constrainedlayout_guide.html for more details"
453482
]
454483
},
455484
{
@@ -458,15 +487,13 @@
458487
"metadata": {},
459488
"outputs": [],
460489
"source": [
461-
"fig, axes = plt.subplots(nrows=1, ncols=2)\n",
490+
"fig, axes = plt.subplots(nrows=1, ncols=2, layout=\"constrained\")\n",
462491
"\n",
463492
"for ax in axes:\n",
464493
" ax.plot(x, y, \"r\")\n",
465494
" ax.set_xlabel(\"x\")\n",
466495
" ax.set_ylabel(\"y\")\n",
467-
" ax.set_title(\"title\")\n",
468-
"\n",
469-
"fig.tight_layout();"
496+
" ax.set_title(\"title\")"
470497
]
471498
},
472499
{
@@ -487,7 +514,7 @@
487514
"cell_type": "markdown",
488515
"metadata": {},
489516
"source": [
490-
"`matplotlib` allows the aspect ratio, DPI and figure size to be specified when the `Figure` object is created, using the `figsize` and `dpi` keyword arguments. `figsize` is a tuple of the width and height of the figure in inches, and `dpi` is the dots-per-inch (pixel per inch). To create an 800x400 pixel, 100 dots-per-inch figure, we can do: "
517+
"`matplotlib` allows the aspect ratio, DPI and figure size to be specified when the `Figure` object is created, using the `figsize` and `dpi` keyword arguments. `figsize` is a tuple of the width and height of the figure in inches, and `dpi` is the dots-per-inch (pixel per inch). To create an 400x400 pixel, 100 dots-per-inch figure, we can do: "
491518
]
492519
},
493520
{
@@ -496,7 +523,7 @@
496523
"metadata": {},
497524
"outputs": [],
498525
"source": [
499-
"fig, axes = plt.subplots(figsize=(12, 3), dpi=100)\n",
526+
"fig, axes = plt.subplots(figsize=(4, 4), dpi=100)\n",
500527
"\n",
501528
"axes.plot(x, y, \"r\")\n",
502529
"axes.set_xlabel(\"x\")\n",
@@ -555,7 +582,7 @@
555582
"metadata": {},
556583
"outputs": [],
557584
"source": [
558-
"fig.savefig(output_path / \"filename.svg\")"
585+
"fig.savefig(output_path / \"filename.pdf\")"
559586
]
560587
},
561588
{
@@ -616,8 +643,8 @@
616643
"axes[1].set_title(\"tight axes\")\n",
617644
"\n",
618645
"axes[2].plot(x, x**2, x, x**3)\n",
619-
"axes[2].set_ylim([0, 60])\n",
620-
"axes[2].set_xlim([2, 3])\n",
646+
"axes[2].set_ylim(0, 60)\n",
647+
"axes[2].set_xlim(2, 3)\n",
621648
"axes[2].set_title(\"custom axes range\");"
622649
]
623650
},
@@ -650,8 +677,20 @@
650677
"cell_type": "markdown",
651678
"metadata": {},
652679
"source": [
653-
"Logarithmic scales can also be specified using `semilogx()`, `semilogy()`, or `loglog()`. What are the differences in the figures plotted using `.set_yscale(\"log\")` and `.semilogy()`?\n",
654-
"\n",
680+
"Logarithmic scales can also be specified using `semilogx()`, `semilogy()`, or `loglog()`. What are the differences in the figures plotted using `.set_yscale(\"log\")` and `.semilogy()`?"
681+
]
682+
},
683+
{
684+
"cell_type": "code",
685+
"execution_count": null,
686+
"metadata": {},
687+
"outputs": [],
688+
"source": []
689+
},
690+
{
691+
"cell_type": "markdown",
692+
"metadata": {},
693+
"source": [
655694
"### Placement of ticks and custom tick labels\n",
656695
"\n",
657696
"The axis ticks can be explicitly set using with `set_xticks` and `set_yticks`, which both take a list of values for where on the axis the ticks are to be placed. The `set_xticklabels` and `set_yticklabels` methods can be used to provide a list of custom text labels for each tick location:"
@@ -683,7 +722,7 @@
683722
"cell_type": "markdown",
684723
"metadata": {},
685724
"source": [
686-
"There are a number of more advanced methods for controlling major and minor tick placement in `matplotlib` figures, such as automatic placement according to different policies. See http://`matplotlib`.org/api/ticker_api.html for details.\n",
725+
"There are a number of more advanced methods for controlling major and minor tick placement in `matplotlib` figures, such as automatic placement according to different policies. See http://matplotlib.org/api/ticker_api.html for details.\n",
687726
"\n",
688727
"### Axis grid\n",
689728
"\n",
@@ -727,8 +766,15 @@
727766
"ax1.plot(x, x**2, lw=2, color=\"blue\")\n",
728767
"ax1.set_ylabel(r\"area $(m^2)$\", fontsize=18, color=\"blue\")\n",
729768
"for label in ax1.get_yticklabels():\n",
730-
" label.set_color(\"blue\")\n",
731-
"\n",
769+
" label.set_color(\"blue\")\n"
770+
]
771+
},
772+
{
773+
"cell_type": "code",
774+
"execution_count": null,
775+
"metadata": {},
776+
"outputs": [],
777+
"source": [
732778
"ax2 = ax1.twinx()\n",
733779
"ax2.plot(x, x**3, lw=2, color=\"red\")\n",
734780
"ax2.set_ylabel(r\"volume $(m^3)$\", fontsize=18, color=\"red\")\n",
@@ -742,7 +788,7 @@
742788
"source": [
743789
"## Other 2D plot styles\n",
744790
"\n",
745-
"In addition to the regular `plot` method, there are a number of other functions for generating different kind of plots. See the `matplotlib` plot gallery for a complete list of available plot types: http://`matplotlib`.org/gallery.html. Some of the more useful ones are show below:"
791+
"In addition to the regular `plot` method, there are a number of other functions for generating different kind of plots. See the `matplotlib` plot gallery for a complete list of available plot types: http://matplotlib.org/gallery.html. Some of the more useful ones are show below:"
746792
]
747793
},
748794
{
@@ -801,7 +847,7 @@
801847
"source": [
802848
"## Text annotation\n",
803849
"\n",
804-
"Annotating text in `matplotlib` figures can be done using the `text` function. It supports LaTeX formatting just like axis label texts and titles:"
850+
"Annotating text in `matplotlib` figures can be done using the `annotate` function. It supports LaTeX formatting just like axis label texts and titles:"
805851
]
806852
},
807853
{
@@ -814,8 +860,9 @@
814860
"\n",
815861
"ax.plot(xx, xx**2, xx, xx**3)\n",
816862
"\n",
817-
"ax.text(0.15, 0.2, r\"$\\alpha y=x^2$\", fontsize=20, color=\"blue\")\n",
818-
"ax.text(0.65, 0.1, r\"$y=x^3$\", fontsize=20, color=\"green\");"
863+
"ax.annotate(text=r'$\\alpha y=x^2$', xy=(0.5, 0.2), fontsize=20, color='tab:blue', va='bottom', ha='right')\n",
864+
"ax.annotate(r'$y=x^3$', xy=(xx[25], (xx**4)[25]), xytext=(0.7, -0.2), fontsize=20, color='tab:orange',\n",
865+
" arrowprops=dict(arrowstyle='->'));"
819866
]
820867
},
821868
{
@@ -824,7 +871,7 @@
824871
"source": [
825872
"## Colormap and contour figures\n",
826873
"\n",
827-
"Colormaps and contour figures are useful for plotting functions of two variables. A colormap will be used to encode one dimension of the data in most of these functions. There are a number of predefined colormaps. It is relatively straightforward to define custom colormaps. For a list of pre-defined colormaps, see: http://www.scipy.org/Cookbook/`matplotlib`/Show_colormaps"
874+
"Colormaps and contour figures are useful for plotting functions of two variables. A colormap will be used to encode one dimension of the data in most of these functions. There are a number of predefined colormaps. It is relatively straightforward to define custom colormaps. For a list of pre-defined colormaps, see: http://www.scipy.org/Cookbook/matplotlib/Show_colormaps"
828875
]
829876
},
830877
{
@@ -862,7 +909,7 @@
862909
"cell_type": "markdown",
863910
"metadata": {},
864911
"source": [
865-
"### pcolor"
912+
"### pcolormesh"
866913
]
867914
},
868915
{
@@ -873,11 +920,11 @@
873920
"source": [
874921
"fig, ax = plt.subplots()\n",
875922
"\n",
876-
"p = ax.pcolor(\n",
877-
" X / (2 * np.pi),\n",
878-
" Y / (2 * np.pi),\n",
923+
"p = ax.pcolormesh(\n",
924+
" X / (2 * np.pi), # corners of quadrilaterals\n",
925+
" Y / (2 * np.pi), # corners of quadrilaterals\n",
879926
" Z,\n",
880-
" cmap=plt.cm.RdBu,\n",
927+
" cmap='viridis',\n",
881928
" vmin=abs(Z).min(),\n",
882929
" vmax=abs(Z).max(),\n",
883930
")\n",
@@ -899,14 +946,14 @@
899946
"source": [
900947
"fig, ax = plt.subplots()\n",
901948
"\n",
902-
"im = plt.imshow(\n",
949+
"im = ax.imshow(\n",
903950
" Z,\n",
904951
" cmap=plt.cm.RdBu,\n",
905952
" vmin=abs(Z).min(),\n",
906953
" vmax=abs(Z).max(),\n",
907954
" extent=[0, 1, 0, 1],\n",
955+
" interpolation=\"bilinear\",\n",
908956
")\n",
909-
"im.set_interpolation(\"bilinear\")\n",
910957
"\n",
911958
"cb = fig.colorbar(im, ax=ax)"
912959
]
@@ -1121,23 +1168,16 @@
11211168
" ax.plot(\n",
11221169
" xx, yy, lw=0, marker=\"o\", ms=4, mfc=\"red\", mec=\"red\", clip_on=False\n",
11231170
" )\n",
1124-
"\n",
1171+
" \n",
1172+
" ax.set_title(f'Page {idx + 1} - {xx:6.2f} $\\pi$')\n",
11251173
" pdf.savefig() # saves the current figure into a pdf page\n",
11261174
" plt.close()"
11271175
]
1128-
},
1129-
{
1130-
"cell_type": "markdown",
1131-
"metadata": {},
1132-
"source": [
1133-
"\n",
1134-
"\n"
1135-
]
11361176
}
11371177
],
11381178
"metadata": {
11391179
"kernelspec": {
1140-
"display_name": "pyclass",
1180+
"display_name": "lisus_p2",
11411181
"language": "python",
11421182
"name": "python3"
11431183
},
@@ -1151,7 +1191,7 @@
11511191
"name": "python",
11521192
"nbconvert_exporter": "python",
11531193
"pygments_lexer": "ipython3",
1154-
"version": "3.11.7"
1194+
"version": "3.11.10"
11551195
}
11561196
},
11571197
"nbformat": 4,

0 commit comments

Comments
 (0)