Merge pull request #10 from vi3itor/update-matplotlib-tutorial

Update matplotlib tutorial
main
Aurélien Geron 2022-05-17 11:05:36 +12:00 committed by GitHub
commit cf964f0303
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 40 additions and 45 deletions

View File

@ -30,7 +30,7 @@
},
"source": [
"# Table of Contents\n",
" <p><div class=\"lev1\"><a href=\"#Plotting-your-first-graph\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Plotting your first graph</a></div><div class=\"lev1\"><a href=\"#Line-style-and-color\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Line style and color</a></div><div class=\"lev1\"><a href=\"#Saving-a-figure\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Saving a figure</a></div><div class=\"lev1\"><a href=\"#Subplots\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Subplots</a></div><div class=\"lev1\"><a href=\"#Multiple-figures\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Multiple figures</a></div><div class=\"lev1\"><a href=\"#Pyplot's-state-machine:-implicit-vs-explicit\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Pyplot's state machine: implicit <em>vs</em> explicit</a></div><div class=\"lev1\"><a href=\"#Pylab-vs-Pyplot-vs-Matplotlib\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Pylab <em>vs</em> Pyplot <em>vs</em> Matplotlib</a></div><div class=\"lev1\"><a href=\"#Drawing-text\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Drawing text</a></div><div class=\"lev1\"><a href=\"#Legends\"><span class=\"toc-item-num\">9&nbsp;&nbsp;</span>Legends</a></div><div class=\"lev1\"><a href=\"#Non-linear-scales\"><span class=\"toc-item-num\">10&nbsp;&nbsp;</span>Non linear scales</a></div><div class=\"lev1\"><a href=\"#Ticks-and-tickers\"><span class=\"toc-item-num\">11&nbsp;&nbsp;</span>Ticks and tickers</a></div><div class=\"lev1\"><a href=\"#Polar-projection\"><span class=\"toc-item-num\">12&nbsp;&nbsp;</span>Polar projection</a></div><div class=\"lev1\"><a href=\"#3D-projection\"><span class=\"toc-item-num\">13&nbsp;&nbsp;</span>3D projection</a></div><div class=\"lev1\"><a href=\"#Scatter-plot\"><span class=\"toc-item-num\">14&nbsp;&nbsp;</span>Scatter plot</a></div><div class=\"lev1\"><a href=\"#Lines\"><span class=\"toc-item-num\">15&nbsp;&nbsp;</span>Lines</a></div><div class=\"lev1\"><a href=\"#Histograms\"><span class=\"toc-item-num\">16&nbsp;&nbsp;</span>Histograms</a></div><div class=\"lev1\"><a href=\"#Images\"><span class=\"toc-item-num\">17&nbsp;&nbsp;</span>Images</a></div><div class=\"lev1\"><a href=\"#Animations\"><span class=\"toc-item-num\">18&nbsp;&nbsp;</span>Animations</a></div><div class=\"lev1\"><a href=\"#Saving-animations-to-video-files\"><span class=\"toc-item-num\">19&nbsp;&nbsp;</span>Saving animations to video files</a></div><div class=\"lev1\"><a href=\"#What-next?\"><span class=\"toc-item-num\">20&nbsp;&nbsp;</span>What next?</a></div>"
" <p><div class=\"lev1\"><a href=\"#Plotting-your-first-graph\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Plotting your first graph</a></div><div class=\"lev1\"><a href=\"#Line-style-and-color\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Line style and color</a></div><div class=\"lev1\"><a href=\"#Saving-a-figure\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Saving a figure</a></div><div class=\"lev1\"><a href=\"#Subplots\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Subplots</a></div><div class=\"lev1\"><a href=\"#Multiple-figures\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Multiple figures</a></div><div class=\"lev1\"><a href=\"#Pyplot's-state-machine:-implicit-vs-explicit\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Pyplot's state machine: implicit <em>vs</em> explicit</a></div><div class=\"lev1\"><a href=\"#Pylab-vs-Pyplot-vs-Matplotlib\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Pylab <em>vs</em> Pyplot <em>vs</em> Matplotlib</a></div><div class=\"lev1\"><a href=\"#Drawing-text\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Drawing text</a></div><div class=\"lev1\"><a href=\"#Legends\"><span class=\"toc-item-num\">9&nbsp;&nbsp;</span>Legends</a></div><div class=\"lev1\"><a href=\"#Non-linear-scales\"><span class=\"toc-item-num\">10&nbsp;&nbsp;</span>Non-linear scales</a></div><div class=\"lev1\"><a href=\"#Ticks-and-tickers\"><span class=\"toc-item-num\">11&nbsp;&nbsp;</span>Ticks and tickers</a></div><div class=\"lev1\"><a href=\"#Polar-projection\"><span class=\"toc-item-num\">12&nbsp;&nbsp;</span>Polar projection</a></div><div class=\"lev1\"><a href=\"#3D-projection\"><span class=\"toc-item-num\">13&nbsp;&nbsp;</span>3D projection</a></div><div class=\"lev1\"><a href=\"#Scatter-plot\"><span class=\"toc-item-num\">14&nbsp;&nbsp;</span>Scatter plot</a></div><div class=\"lev1\"><a href=\"#Lines\"><span class=\"toc-item-num\">15&nbsp;&nbsp;</span>Lines</a></div><div class=\"lev1\"><a href=\"#Histograms\"><span class=\"toc-item-num\">16&nbsp;&nbsp;</span>Histograms</a></div><div class=\"lev1\"><a href=\"#Images\"><span class=\"toc-item-num\">17&nbsp;&nbsp;</span>Images</a></div><div class=\"lev1\"><a href=\"#Animations\"><span class=\"toc-item-num\">18&nbsp;&nbsp;</span>Animations</a></div><div class=\"lev1\"><a href=\"#Saving-animations-to-video-files\"><span class=\"toc-item-num\">19&nbsp;&nbsp;</span>Saving animations to video files</a></div><div class=\"lev1\"><a href=\"#What's-next?\"><span class=\"toc-item-num\">20&nbsp;&nbsp;</span>What's next?</a></div>"
]
},
{
@ -102,7 +102,7 @@
"**Note**:\n",
"\n",
"> Matplotlib can output graphs using various backend graphics libraries, such as Tk, wxPython, etc. When running Python using the command line, you may want to specify which backend to use right after importing matplotlib and before plotting anything. For example, to use the Tk backend, run `matplotlib.use(\"TKAgg\")`.\n",
"> However, in a Jupyter notebook, things are easier: importing `import matplotlib.pyplot` automatically registers Jupyter itself as a backend, so the graphs show up directly within the notebook. This used to require running `%matplotlib inline`, so you'll still see it in some notebooks, but it's not needed anymore."
"> However, in a Jupyter notebook, things are easier: importing `import matplotlib.pyplot` automatically registers Jupyter itself as a backend, so the graphs show up directly within the notebook. It used to require running `%matplotlib inline`, so you'll still see it in some notebooks, but it's not needed anymore."
]
},
{
@ -281,7 +281,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"You can pass a 3rd argument to change the line's style and color.\n",
"You can pass the 3rd argument to change the line's style and color.\n",
"For example `\"g--\"` means \"green dashed line\"."
]
},
@ -382,7 +382,7 @@
"metadata": {},
"source": [
"You can also draw simple points instead of lines. Here's an example with green dashes, red dotted line and blue triangles.\n",
"Check out [the documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot) for the full list of style & color options."
"Check out [the documentation](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot) for the full list of style & color options."
]
},
{
@ -413,7 +413,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"The plot function returns a list of `Line2D` objects (one for each line). You can set extra attributes on these lines, such as the line width, the dash style or the alpha level. See the full list of attributes in [the documentation](http://matplotlib.org/users/pyplot_tutorial.html#controlling-line-properties)."
"The plot function returns a list of `Line2D` objects (one for each line). You can set extra properties on these lines, such as the line width, the dash style or the alpha level. See the full list of properties in [the documentation](https://matplotlib.org/stable/tutorials/introductory/pyplot.html#controlling-line-properties)."
]
},
{
@ -450,7 +450,7 @@
"metadata": {},
"source": [
"# Saving a figure\n",
"Saving a figure to disk is as simple as calling [`savefig`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig) with the name of the file (or a file object). The available image formats depend on the graphics backend you use."
"Saving a figure to disk is as simple as calling [`savefig`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html) with the name of the file (or a file object). The available image formats depend on the graphics backend you use."
]
},
{
@ -513,7 +513,7 @@
"plt.plot(x, x)\n",
"plt.subplot(2, 2, 2) # 2 rows, 2 columns, 2nd subplot = top right\n",
"plt.plot(x, x**2)\n",
"plt.subplot(2, 2, 3) # 2 rows, 2 columns, 3rd subplot = bottow left\n",
"plt.subplot(2, 2, 3) # 2 rows, 2 columns, 3rd subplot = bottom left\n",
"plt.plot(x, x**3)\n",
"plt.subplot(2, 2, 4) # 2 rows, 2 columns, 4th subplot = bottom right\n",
"plt.plot(x, x**4)\n",
@ -566,7 +566,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"If you need more complex subplot positionning, you can use `subplot2grid` instead of `subplot`. You specify the number of rows and columns in the grid, then your subplot's position in that grid (top-left = (0,0)), and optionally how many rows and/or columns it spans. For example:"
"If you need more complex subplot positioning, you can use `subplot2grid` instead of `subplot`. You specify the number of rows and columns in the grid, then your subplot's position in that grid (top-left = (0,0)), and optionally how many rows and/or columns it spans. For example:"
]
},
{
@ -603,7 +603,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"If you need even more flexibility in subplot positioning, check out the [GridSpec documentation](http://matplotlib.org/users/gridspec.html)"
"If you need even more flexibility in subplot positioning, check out the [corresponding matplotlib tutorial](https://matplotlib.org/stable/tutorials/intermediate/arranging_axes.html)."
]
},
{
@ -781,7 +781,7 @@
"\n",
"Pyplot provides a number of tools to plot graphs, including the state-machine interface to the underlying object-oriented plotting library.\n",
"\n",
"Pylab is a convenience module that imports matplotlib.pyplot and NumPy in a single name space. You will find many examples using pylab, but it is no longer recommended (because *explicit* imports are better than *implicit* ones)."
"Pylab is a convenience module that imports matplotlib.pyplot and NumPy within a single namespace. You will find many examples using pylab, but it is now [strongly discouraged](https://matplotlib.org/stable/api/index.html#module-pylab) (because *explicit* imports are better than *implicit* ones)."
]
},
{
@ -789,7 +789,7 @@
"metadata": {},
"source": [
"# Drawing text\n",
"You can call `text` to add text at any location in the graph. Just specify the horizontal and vertical coordinates and the text, and optionally some extra attributes. Any text in matplotlib may contain TeX equation expressions, see [the documentation](http://matplotlib.org/users/mathtext.html) for more details."
"You can call `text` to add text at any location in the graph. Just specify the horizontal and vertical coordinates and the text, and optionally some extra arguments. Any text in matplotlib may contain TeX equation expressions, see [the documentation](https://matplotlib.org/stable/tutorials/text/mathtext.html) for more details."
]
},
{
@ -832,9 +832,9 @@
"source": [
"* Note: `ha` is an alias for `horizontalalignment`\n",
"\n",
"For more text properties, visit [the documentation](http://matplotlib.org/users/text_props.html#text-properties).\n",
"For more text properties, visit [the documentation](https://matplotlib.org/stable/tutorials/text/text_props.html).\n",
"\n",
"It is quite frequent to annotate elements of a graph, such as the beautiful point above. The `annotate` function makes this easy: just indicate the location of the point of interest, and the position of the text, plus optionally some extra attributes for the text and the arrow."
"Every so often it is required to annotate elements of a graph, such as the beautiful point above. The `annotate` function makes it easy: just indicate the location of the point of interest, and the position of the text, plus optionally some extra arguments for the text and the arrow."
]
},
{
@ -867,7 +867,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also add a bounding box around your text by using the `bbox` attribute:"
"You can also add a bounding box around your text by using the `bbox` argument:"
]
},
{
@ -906,7 +906,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Just for fun, if you want an [xkcd](http://xkcd.com)-style plot, just draw within a `with plt.xkcd()` section:"
"Just for fun, if you want a [xkcd](https://xkcd.com)-style plot, just draw within a `with plt.xkcd()` section:"
]
},
{
@ -979,8 +979,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# Non linear scales\n",
"Matplotlib supports non linear scales, such as logarithmic or logit scales."
"# Non-linear scales\n",
"Matplotlib supports non-linear scales, such as logarithmic or logit scales."
]
},
{
@ -1076,10 +1076,9 @@
"metadata": {},
"source": [
"# Ticks and tickers\n",
"The axes have little marks called \"ticks\". To be precise, \"ticks\" are the *locations* of the marks (eg. (-1, 0, 1)), \"tick lines\" are the small lines drawn at those locations, \"tick labels\" are the labels drawn next to the tick lines, and \"tickers\" are objects that are capable of deciding where to place ticks. The default tickers typically do a pretty good job at placing ~5 to 8 ticks at a reasonable distance from one another.\n",
"The axes have little marks called \"ticks\". To be precise, \"ticks\" are the *locations* of the marks (e.g. (-1, 0, 1)), \"tick lines\" are the small lines drawn at those locations, \"tick labels\" are the labels drawn next to the tick lines, and \"tickers\" are objects that are capable of deciding where to place ticks. The default tickers typically do a pretty good job at placing ~5 to 8 ticks at a reasonable distance from one another.\n",
"\n",
"But sometimes you need more control (eg. there are too many tick labels on the logit graph above). Fortunately, matplotlib gives you full control over ticks. You can even activate minor ticks.\n",
"\n"
"But sometimes you need more control (e.g. there are too many tick labels on the logit graph above). Fortunately, matplotlib gives you full control over ticks. You can even activate minor ticks.\n"
]
},
{
@ -1122,10 +1121,8 @@
"ax.xaxis.set_ticks([-2, 0, 1, 2])\n",
"ax.yaxis.set_ticks(np.arange(-5, 5, 1))\n",
"ax.yaxis.set_ticklabels([\"min\", -4, -3, -2, -1, 0, 1, 2, 3, \"max\"])\n",
"plt.title(\"Manual ticks and tick labels\\n(plus minor ticks) on the y-axis\")\n",
"\n",
"\n",
"plt.grid(True)\n",
"plt.title(\"Manual ticks and tick labels\\n(plus minor ticks) on the y-axis\")\n",
"\n",
"plt.show()"
]
@ -1135,7 +1132,7 @@
"metadata": {},
"source": [
"# Polar projection\n",
"Drawing a polar graph is as easy as setting the `projection` attribute to `\"polar\"` when creating the subplot."
"Drawing a polar graph is as easy as setting the `projection` argument to `\"polar\"` when creating the subplot."
]
},
{
@ -1172,7 +1169,7 @@
"source": [
"# 3D projection\n",
"\n",
"Plotting 3D graphs is quite straightforward. You need to import `Axes3D`, which registers the `\"3d\"` projection. Then create a subplot setting the `projection` to `\"3d\"`. This returns an `Axes3DSubplot` object, which you can use to call `plot_surface`, giving x, y, and z coordinates, plus optional attributes."
"Plotting 3D graphs is quite straightforward: when creating a subplot, set the `projection` to `\"3d\"`. It returns a 3D axes object, which you can use to call `plot_surface`, providing x, y, and z coordinates, plus other optional arguments. For more information on generating 3D plots, check out the [matplotlib tutorial](https://matplotlib.org/stable/tutorials/toolkits/mplot3d.html)."
]
},
{
@ -1196,8 +1193,6 @@
}
],
"source": [
"from mpl_toolkits.mplot3d import Axes3D\n",
"\n",
"x = np.linspace(-5, 5, 50)\n",
"y = np.linspace(-5, 5, 50)\n",
"X, Y = np.meshgrid(x, y)\n",
@ -1318,7 +1313,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"And as usual there are a number of other attributes you can set, such as the fill and edge colors and the alpha level."
"And as usual there are a number of other arguments you can provide, such as the fill and edge colors and the alpha level."
]
},
{
@ -1381,11 +1376,11 @@
}
],
"source": [
"def plot_line(axis, slope, intercept, **kargs):\n",
"def plot_line(axis, slope, intercept, **kwargs):\n",
" xmin, xmax = axis.get_xlim()\n",
" plt.plot([xmin, xmax],\n",
" [xmin*slope+intercept, xmax*slope+intercept],\n",
" **kargs)\n",
" **kwargs)\n",
"\n",
"x = np.random.randn(1000)\n",
"y = 0.5*x + 5 + np.random.randn(1000) * 2\n",
@ -1486,7 +1481,7 @@
"# Images\n",
"Reading, generating and plotting images in matplotlib is quite straightforward.\n",
"\n",
"To read an image, just import the `matplotlib.image` module, and call its `imread` function, passing it the file name (or file object). This returns the image data, as a NumPy array. Let's try this with the `my_square_function.png` image we saved earlier."
"To read an image, just import the `matplotlib.image` module, and call its `imread` function, passing it the file name (or file object). It returns the image data, as a NumPy array. Let's try it with the `my_square_function.png` image we saved earlier."
]
},
{
@ -1513,7 +1508,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"We have loaded a 288x432 image. Each pixel is represented by a 4-element array: red, green, blue, and alpha levels, stored as 32-bit floats between 0 and 1. Now all we need to do is to call `imshow`:"
"We have loaded a 288x432 image. Each pixel is represented by a 4-element array: red, green, blue, and alpha levels, stored as 32-bit floats between 0 and 1. Now all we need to do is to call `imshow`:"
]
},
{
@ -1546,13 +1541,6 @@
"Tadaaa! You may want to hide the axes when you are displaying an image:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Under the hood, `imread()` uses the Python Image Library (PIL), and Matplotlib's documentation now recommends using PIL directly:"
]
},
{
"cell_type": "code",
"execution_count": 38,
@ -1577,6 +1565,13 @@
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Under the hood, `imread()` uses the Python Image Library (PIL), and Matplotlib's documentation now recommends using PIL directly:"
]
},
{
"cell_type": "code",
"execution_count": 39,
@ -1743,7 +1738,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Since the `img` array is just quite small (20x30), when the `imshow` function displays it, it grows the image to the figure's size. Imagine stretching the original image, leaving blanks between the original pixels. How does imshow fill the blanks? Well, by default, it just colors each blank pixel using the color of the nearest non-blank pixel. This technique can lead to pixelated images. If you prefer, you can use a different interpolation method, such as [bilinear interpolation](https://en.wikipedia.org/wiki/Bilinear_interpolation) to fill the blank pixels. This leads to blurry edges, which many be nicer in some cases:"
"Since the `img` array is just quite small (20x30), when the `imshow` function displays it, it grows the image to the figure's size. Imagine stretching the original image, leaving blanks between the original pixels. How does imshow fill the blanks? Well, by default, it just colors each blank pixel using the color of the nearest non-blank pixel. This technique can lead to pixelated images. If you prefer, you can use a different interpolation method, such as [bilinear interpolation](https://en.wikipedia.org/wiki/Bilinear_interpolation) to fill the blank pixels. This leads to blurry edges, which may be nicer in some cases:"
]
},
{
@ -1906,7 +1901,7 @@
"metadata": {},
"source": [
"# Saving animations to video files\n",
"Matplotlib relies on 3rd-party libraries to write videos such as [FFMPEG](https://www.ffmpeg.org/) or [ImageMagick](https://imagemagick.org/). In this example we will be using FFMPEG so be sure to install it first. To save the animation to the GIF format, you would need ImageMagick."
"Matplotlib relies on 3rd-party libraries to write videos such as [FFMPEG](https://www.ffmpeg.org/) or [ImageMagick](https://imagemagick.org/). In the following example we will be using FFMPEG so be sure to install it first. To save the animation to the GIF format, you would need ImageMagick."
]
},
{
@ -1924,8 +1919,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"# What next?\n",
"Now you know all the basics of matplotlib, but there are many more options available. The best way to learn more, is to visit the [gallery](http://matplotlib.org/gallery.html), look at the images, choose a plot that you are interested in, then just copy the code in a Jupyter notebook and play around with it."
"# What's next?\n",
"Now you know all the basics of matplotlib, but there are many more options available. The best way to learn more, is to visit the [gallery](https://matplotlib.org/stable/gallery/index.html), look at the images, choose a plot that you are interested in, then just copy the code in a Jupyter notebook and play around with it."
]
}
],