diff --git a/README.html b/README.html index a5ce63e..3b5d989 100644 --- a/README.html +++ b/README.html @@ -3,7 +3,7 @@
- +
+
Table of Contents
+Table of Contents
Sources are available from @@ -30,15 +30,14 @@
All code and material is licensed under a Creative Commons Attribution-ShareAlike 4.0.
You can test your installation before the tutorial using the check-installation.py script.
-Tutorial can be read at http://www.labri.fr/perso/nrougier/teaching/matplotlib/matplotlib.html
See also:
matplotlib is probably the single most used Python package for 2D-graphics. It provides both a very quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore @@ -47,7 +46,7 @@
IPython is an enhanced interactive Python shell that has lots of interesting features including named inputs and outputs, access to -shell commands, improved debugging and many more. It allows +shell commands, improved debugging and much more. It allows interactive matplotlib sessions that have Matlab/Mathematica-like functionality.
In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default settings, we'll enrich the figure step by step to make it nicer.
-First step is to get the data for the sine and cosine functions:
+The first step is to get the data for the sine and cosine functions:
import numpy as np -X = np.linspace(-np.pi, np.pi, 256,endpoint=True) -C,S = np.cos(X), np.sin(X) +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +C, S = np.cos(X), np.sin(X)-
X is now a numpy array with 256 values ranging from -π to +π (included). C is +
X is now a NumPy array with 256 values ranging from -π to +π (included). C is the cosine (256 values) and S is the sine (256 values).
To run the example, you can download each of the examples and run it using:
@@ -79,7 +78,7 @@Simple plot
You can get source for each step by clicking on the corresponding figure.
Using defaults
-+Documentation
- plot tutorial
@@ -94,10 +93,10 @@Using defaults
are rather good in most cases, you may want to modify some properties for specific cases.-import numpy as np -import matplotlib.pyplot as plt +import numpy as np +import matplotlib.pyplot as plt -X = np.linspace(-np.pi, np.pi, 256, endpoint=True) +X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C,S = np.cos(X), np.sin(X) plt.plot(X,C) @@ -108,7 +107,7 @@Using defaults
Instantiating defaults
-+Documentation
- Customizing matplotlib
@@ -121,16 +120,16 @@Instantiating defaults
to explore their affect (see Line properties and Line styles below).# Imports -import numpy as np -import matplotlib.pyplot as plt +import numpy as np +import matplotlib.pyplot as plt # Create a new figure of size 8x6 points, using 100 dots per inch -plt.figure(figsize=(8,6), dpi=80) +plt.figure(figsize=(8,6), dpi=100) # Create a new subplot from a grid of 1x1 plt.subplot(111) -X = np.linspace(-np.pi, np.pi, 256,endpoint=True) +X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C,S = np.cos(X), np.sin(X) # Plot cosine using blue color with a continuous line of width 1 (pixels) @@ -143,13 +142,13 @@Instantiating defaults
plt.xlim(-4.0,4.0) # Set x ticks -plt.xticks(np.linspace(-4,4,9,endpoint=True)) +plt.xticks(np.linspace(-4,4,9,endpoint=True)) # Set y limits plt.ylim(-1.0,1.0) # Set y ticks -plt.yticks(np.linspace(-1,1,5,endpoint=True)) +plt.yticks(np.linspace(-1,1,5,endpoint=True)) # Save figure using 72 dots per inch # savefig("../figures/exercice_2.png",dpi=72) @@ -160,7 +159,7 @@Instantiating defaults
Changing colors and line widths
-+Documentation
- Controlling line properties
@@ -168,7 +167,7 @@Changing colors and line widths
-
First step, we want to have the cosine in blue and the sine in red and a +
As a first step, we want to have the cosine in blue and the sine in red and a slightly thicker line for both of them. We'll also slightly alter the figure size to make it more horizontal.
@@ -181,7 +180,7 @@Changing colors and line widths
Setting limits
-+Documentation
- xlim() command
@@ -200,7 +199,7 @@Setting limits
Setting ticks
-+Documentation
- xticks() command
@@ -222,7 +221,7 @@Setting ticks
Setting tick labels
-+Documentation
- Working with text
@@ -249,7 +248,7 @@Setting tick labels
Moving spines
-+Documentation
- Spines
@@ -278,7 +277,7 @@Moving spines
Adding a legend
-+Documentation
- Legend guide
@@ -301,7 +300,7 @@Adding a legend
Annotate some points
-+Documentation
- Annotating axis
@@ -309,7 +308,7 @@Annotate some points
-
Let's annotate some interesting points using the annotate command. We chose the +
Let's annotate some interesting points using the annotate command. We choose the 2π/3 value and we want to annotate both the sine and the cosine. We'll first draw a marker on the curve as well as a straight dotted line. Then, we'll use the annotate command to display some text with an arrow.
@@ -337,7 +336,7 @@Annotate some points
Devil is in the details
-+Documentation
- Artists
@@ -359,7 +358,7 @@Devil is in the details
-Figures, Subplots, Axes and Ticks
+Figures, Subplots, Axes and Ticks
So far we have used implicit figure and axes creation. This is handy for fast plots. We can have more control over the display using figure, subplot, and axes explicitly. A figure in matplotlib means the whole window in the user @@ -418,7 +417,7 @@
Figures
The defaults can be specified in the resource file and will be used most of the time. Only the number of the figure is frequently changed.
When you work with the GUI you can close a figure by clicking on the x in the -upper right corner. But you can close a figure programmatically by calling +upper right corner. You can also close a figure programmatically by calling close. Depending on the argument it closes (1) the current figure (no argument), (2) a specific figure (figure number or figure instance as argument), or (3) all figures (all as argument).
@@ -448,13 +447,13 @@Ticks
figures. Matplotlib provides a totally configurable system for ticks. There are tick locators to specify where ticks should appear and tick formatters to give ticks the appearance you want. Major and minor ticks can be located and -formatted independently from each other. Per default minor ticks are not shown, +formatted independently from each other. By default minor ticks are not shown, i.e. there is only an empty list for them because it is as NullLocator (see below).Tick Locators
There are several locators for different kind of requirements:
-+
@@ -510,13 +509,13 @@ Tick Locators
-Animation
+Animation
For quite a long time, animation in matplotlib was not an easy task and was done mainly through clever hacks. However, things have started to change since version 1.1 and the introduction of tools for creating animation very intuitively, with the possibility to save them in all kind of formats (but don't -expect to be able to run very complex animation at 60 fps though).
-+expect to be able to run very complex animations at 60 fps though). +Documentation
- See Animation
@@ -538,14 +537,14 @@Drip drop
fig = plt.figure(figsize=(6,6), facecolor='white') # New axis over the whole figure, no frame and a 1:1 aspect ratio -ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1) +ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)Next, we need to create several rings. For this, we can use the scatter plot object that is generally used to visualize points cloud, but we can also use it -to draw rings by specifying we don't have a facecolor. We have also to take -care of initial size and color for each ring such that we have all size between -a minimum and a maximum size and also to make sure the largest ring is almost -transparent.
+to draw rings by specifying we don't have a facecolor. We also have to take +care of initial size and color for each ring such that we have all sizes between +a minimum and a maximum size. In addition, we need to make sure the largest ring +is almost transparent.
# Number of ring @@ -573,10 +572,10 @@Drip drop
ax.set_ylim(0,1), ax.set_yticks([])Now, we need to write the update function for our animation. We know that at -each time step each ring should grow be more transparent while largest ring -should be totally transparent and thus removed. Of course, we won't actually -remove the largest ring but re-use it to set a new ring at a new random -position, with nominal size and color. Hence, we keep the number of ring +each time step each ring should grow and become more transparent while the +largest ring should be totally transparent and thus removed. Of course, we won't +actually remove the largest ring but re-use it to set a new ring at a new random +position, with nominal size and color. Hence, we keep the number of rings constant.
@@ -606,7 +605,7 @@Drip drop
Last step is to tell matplotlib to use this function as an update function for the animation and display the result or save it as a movie:
-animation = FuncAnimation(fig, update, interval=10, blit=True, frames=200) +animation = FuncAnimation(fig, update, interval=10, blit=True, frames=200) # animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40) plt.show()@@ -616,14 +615,14 @@Earthquakes
We'll now use the rain animation to visualize earthquakes on the planet from the last 30 days. The USGS Earthquake Hazards Program is part of the National Earthquake Hazards Reduction Program (NEHRP) and provides several data on their -website. Those data are sorted according to +website. Those data are sorted according to earthquakes magnitude, ranging from significant only down to all earthquakes, major or minor. You would be surprised by the number of minor earthquakes happening every hour on the planet. Since this would represent too much data for us, we'll stick to earthquakes with magnitude > 4.5. At the time of writing, this already represent more than 300 earthquakes in the last 30 days.
First step is to read and convert data. We'll use the urllib library that -allows to open and read remote data. Data on the website use the CSV format +allows us to open and read remote data. Data on the website use the CSV format whose content is given by the first line:
time,latitude,longitude,depth,mag,magType,nst,gap,dmin,rms,net,id,updated,place,type @@ -634,10 +633,9 @@Earthquakes
time of event (ok, that's bad, feel free to send me a PR).import urllib -from mpl_toolkits.basemap import Basemap -# -> http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php -feed = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/" +# -> https://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php +feed = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/" # Significant earthquakes in the last 30 days # url = urllib.request.urlopen(feed + "significant_month.csv") @@ -653,41 +651,52 @@-Earthquakes
# Reading and storage of data data = url.read() -data = data.split(b'\n')[+1:-1] +data = data.split(b'\n')[+1:-1] E = np.zeros(len(data), dtype=[('position', float, 2), - ('magnitude', float, 1)]) + ('magnitude', float)]) for i in range(len(data)): - row = data[i].split(',') + row = data[i].split(b',') E['position'][i] = float(row[2]),float(row[1]) E['magnitude'][i] = float(row[4])Now, we need to draw earth on a figure to show precisely where the earthquake +
Now, we need to draw the earth on a figure to show precisely where the earthquake center is and to translate latitude/longitude in some coordinates matplotlib -can handle. Fortunately, there is the basemap project (that tends to be replaced by the -more complete cartopy) that is really +can handle. Fortunately, there is the basemap project (which is now deprecated in favor +of the cartopy project) that is really simple to install and to use. First step is to define a projection to draw the earth onto a screen (there exists many different projections) and we'll stick to the mill projection which is rather standard for non-specialist like me.
+from mpl_toolkits.basemap import Basemap fig = plt.figure(figsize=(14,10)) ax = plt.subplot(1,1,1) -earth = Basemap(projection='mill') +map = Basemap(projection='mill')Next, we request to draw coastline and fill continents:
-earth.drawcoastlines(color='0.50', linewidth=0.25) -earth.fillcontinents(color='0.95') +map.drawcoastlines(color='0.50', linewidth=0.25) +map.fillcontinents(color='0.95') ++For cartopy, the steps are quite similar:
++import cartopy +ax = plt.axes(projection=cartopy.crs.Miller()) +ax.coastlines(color='0.50', linewidth=0.25) +ax.add_feature(cartopy.feature.LAND, color='0.95') +ax.set_global() +trans = cartopy.crs.PlateCarree()-The earth object will also be used to translate coordinate quite -automatically. We are almost finished. Last step is to adapt the rain code and -put some eye candy:
+We are almost finished. Last step is to adapt the rain code and +put some eye candy. For basemap we use the map object to +transform the coordinates whereas for cartopy we use the transform_point +function of the chosen Miller projection:
P = np.zeros(50, dtype=[('position', float, 2), - ('size', float, 1), - ('growth', float, 1), - ('color', float, 4)]) + ('size', float), + ('growth', float), + ('color', float, 4)]) scat = ax.scatter(P['position'][:,0], P['position'][:,1], P['size'], lw=0.5, edgecolors = P['color'], facecolors='None', zorder=10) @@ -699,7 +708,8 @@Earthquakes
P['size'] += P['growth'] magnitude = E['magnitude'][current] - P['position'][i] = earth(*E['position'][current]) + P['position'][i] = map(*E['position'][current]) if use_basemap else \ + cartopy.crs.Miller().transform_point(*E['position'][current], cartopy.crs.PlateCarree()) P['size'][i] = 5 P['growth'][i]= np.exp(magnitude) * 0.1 @@ -714,7 +724,7 @@Earthquakes
return scat, -animation = FuncAnimation(fig, update, interval=10) +animation = FuncAnimation(fig, update, interval=10, blit=True) plt.show()If everything went well, you should obtain something like this (with animation):
@@ -722,7 +732,7 @@Earthquakes
-Other Types of Plots
+Other Types of Plots
![]()
![]()
@@ -738,13 +748,13 @@
Other Types of Plots
Regular Plots
-
+Hints
You need to use the fill_between command.
Starting from the code below, try to reproduce the graphic on the right taking -care of filled areas:
+care of filled areas.import numpy as np import matplotlib.pyplot as plt @@ -762,7 +772,7 @@Regular Plots
Scatter Plots
-
+@@ -784,7 +794,7 @@Hints
Color is given by angle of (X,Y).
Scatter Plots
Bar Plots
-
+@@ -813,7 +823,7 @@Hints
You need to take care of text alignment.
Bar Plots
Contour Plots
-
+Hints
You need to use the clabel command.
@@ -840,10 +850,10 @@Contour Plots
Imshow
-
+Hints
You need to take care of the origin of the image in the imshow command and -use a colorbar
+use a colorbar.Starting from the code below, try to reproduce the graphic on the right taking care of colormap, image interpolation and origin.
@@ -865,7 +875,7 @@Imshow
Pie Charts
-
+@@ -885,7 +895,7 @@Hints
You need to modify Z.
Pie Charts
Quiver Plots
-
+@@ -924,7 +934,7 @@Hints
You need to draw arrows twice.
Grids
Multi Plots
-
+@@ -944,9 +954,9 @@Hints
You can use several subplots with different partition.
Multi Plots
Polar Axis
-
+Hints
-You only need to modify the axes line
+You only need to modify the axes line.
Starting from the code below, try to reproduce the graphic on the right.
@@ -972,9 +982,9 @@Polar Axis
3D Plots
-
+Starting from the code below, try to reproduce the graphic on the right.
@@ -999,16 +1009,16 @@3D Plots
Text
-
+-Hints
Have a look at the matplotlib logo.
Try to do the same from scratch !
+Try to do the same from scratch!
Click on figure for solution.
-Beyond this tutorial
+Beyond this tutorial
Matplotlib benefits from extensive documentation as well as a large community of users and developpers. Here are some links of interest:
@@ -1126,11 +1136,11 @@Mailing lists
-Quick references
+Quick references
Here is a set of tables that show main properties and styles.
Line properties
-