Commit 389147fd authored by Michiel Cottaar's avatar Michiel Cottaar Committed by Michiel Cottaar
Browse files

fixed many bugs in practical

parent 8d802184
This diff is collapsed.
...@@ -32,34 +32,34 @@ plt.plot? ...@@ -32,34 +32,34 @@ plt.plot?
As you can see there are a lot of options. As you can see there are a lot of options.
The ones you will probably use most often are: The ones you will probably use most often are:
- `linestyle`: how the line is plotted (set to None to omit the line) - `linestyle`: how the line is plotted (set to '' to omit the line)
- `marker`: how the points are plotted (these are not plotted by default) - `marker`: how the points are plotted (these are not plotted by default)
- `color`: what color to use (defaults to cycling through a set of 7 colors) - `color`: what color to use (defaults to cycling through a set of 7 colors)
``` ```
theta = np.linspace(0, 2 * np.pi, 101) theta = np.linspace(0, 2 * np.pi, 101)
plt.plot(np.sin(theta), np.cos(theta)) plt.plot(np.sin(theta), np.cos(theta))
plt.plot([-0.3, 0.3], [0.3, 0.3], marker='o', linestyle=None, size=10) plt.plot([-0.3, 0.3], [0.3, 0.3], marker='o', linestyle='', markersize=20)
plt.plot(0, 0.1, marker='s', color='black') plt.plot(0, -0.1, marker='s', color='black')
plt.plot(0.5 * x, -0.5 * x ** 2 - 0.5, linestyle='--', marker='+', color='yellow') x = np.linspace(-0.5, 0.5, 5)
plt.plot(x, x ** 2 - 0.5, linestyle='--', marker='+', color='red')
``` ```
Because these keywords are so common, you can actually set them directly by passing in a string as the third argument. Because these keywords are so common, you can actually set one or more of them by passing in a string as the third argument.
``` ```
x = np.linspace(0, 1, 11) x = np.linspace(0, 1, 11)
plt.plot(x, x) plt.plot(x, x)
plt.plot(x, x, '--') # sets the linestyle to dashed plt.plot(x, x ** 2, '--') # sets the linestyle to dashed
plt.plot(x, x, 's') # sets the marker to square (and turns off the line) plt.plot(x, x ** 3, 's') # sets the marker to square (and turns off the line)
plt.plot(x, x, 'y:') # sets the linestyle to dotted (i.e., ':') and the color to yellow (i.e., 'y') plt.plot(x, x ** 4, '^y:') # sets the marker to triangles (i.e., '^'), linestyle to dotted (i.e., ':'), and the color to yellow (i.e., 'y')
``` ```
Note in the last line that if you want to define both the color and the marker/linestyle you need to put the color identifier first.
### Scatter plots ### Scatter plots
The main extra feature of `plt.scatter` over `plt.plot` is that you can vary the color and size of the points based on some other variable array: The main extra feature of `plt.scatter` over `plt.plot` is that you can vary the color and size of the points based on some other variable array:
``` ```
x = np.random.rand(30) x = np.random.rand(30)
y = np.random.rand(30) y = np.random.rand(30)
plt.scatter(x, y, x, y) plt.scatter(x, y, x * 30, y)
plt.colorbar() # adds a colorbar plt.colorbar() # adds a colorbar
``` ```
The third argument is the variable determining the color, while the fourth argument is the variable setting the size. The third argument is the variable determining the size, while the fourth argument is the variable setting the color.
### Histograms and bar plots ### Histograms and bar plots
For a simple histogram you can do this: For a simple histogram you can do this:
``` ```
...@@ -85,7 +85,7 @@ plt.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2') ...@@ -85,7 +85,7 @@ plt.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2')
plt.legend(loc='upper left') plt.legend(loc='upper left')
``` ```
> If you want more advanced distribution plots beyond a simple histogram, have a look at the seaborn [gallery](https://seaborn.pydata.org/examples/index.html) to see if they have what you want. > If you want more advanced distribution plots beyond a simple histogram, have a look at the seaborn [gallery](https://seaborn.pydata.org/examples/index.html) for (too?) many options.
### Adding error bars ### Adding error bars
If your data is not completely perfect and has for some obscure reason some uncertainty associated with it, If your data is not completely perfect and has for some obscure reason some uncertainty associated with it,
...@@ -95,7 +95,7 @@ x = np.arange(5) ...@@ -95,7 +95,7 @@ x = np.arange(5)
y1 = [0.3, 0.5, 0.7, 0.1, 0.3] y1 = [0.3, 0.5, 0.7, 0.1, 0.3]
yerr = [0.12, 0.28, 0.1, 0.25, 0.6] yerr = [0.12, 0.28, 0.1, 0.25, 0.6]
xerr = 0.3 xerr = 0.3
plt.error(x, y1, yerr, xerr, marker='s') plt.errorbar(x, y1, yerr, xerr, marker='s', linestyle='')
``` ```
### Shading regions ### Shading regions
An area below a plot can be shaded using `plt.fill` An area below a plot can be shaded using `plt.fill`
...@@ -104,19 +104,19 @@ x = np.linspace(0, 2, 100) ...@@ -104,19 +104,19 @@ x = np.linspace(0, 2, 100)
plt.fill(x, np.sin(x * np.pi)) plt.fill(x, np.sin(x * np.pi))
``` ```
This can be nicely combined with a polar projection, to create nice polar plots: This can be nicely combined with a polar projection, to create 2D orientation distribution functions:
``` ```
plt.subplot(project='polar') plt.subplot(projection='polar')
theta = np.linspace(0, 2 * np.pi, 100) theta = np.linspace(0, 2 * np.pi, 100)
plt.fill(theta, np.exp(-2 * np.cos(theta) ** 2)) plt.fill(theta, np.exp(-2 * np.cos(theta) ** 2))
``` ```
The area between two lines can be shaded using `fill_between`: The area between two lines can be shaded using `fill_between`:
``` ```
x = np.linspace(0, 10, 100) x = np.linspace(0, 10, 1000)
y = 5 * np.sin(x) + x - 0.1 * x ** 2 y = 5 * np.sin(5 * x) + x - 0.1 * x ** 2
yl = x - 0.1 * x ** 2 - 2.5 yl = x - 0.1 * x ** 2 - 5
yu = yl + 5 yu = yl + 10
plt.plot(x, y, 'r') plt.plot(x, y, 'r')
plt.fill_between(x, yl, yu) plt.fill_between(x, yl, yu)
``` ```
...@@ -148,14 +148,16 @@ plt.ylim(reversed(plt.ylim())) ...@@ -148,14 +148,16 @@ plt.ylim(reversed(plt.ylim()))
plt.colorbar() plt.colorbar()
plt.grid('off') plt.grid('off')
``` ```
> It is easier to produce informative brain images using nilearn or fsleyes
### Adding lines, arrows, and text ### Adding lines, arrows, and text
Adding horizontal/vertical lines, arrows, and text: Adding horizontal/vertical lines, arrows, and text:
``` ```
plt.axhline(-1) # horizontal line plt.axhline(-1) # horizontal line
plt.axvline(1) # vertical line plt.axvline(1) # vertical line
plt.arrow(0.2, -0.2, 0.2, -0.8, length_includes_head=True) plt.arrow(0.2, -0.2, 0.2, -0.8, length_includes_head=True, width=0.01)
plt.annotate("line crossing", (1, -1), (1, 1)) # adds both text and arrow plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes, ha='center', va='center')
plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes) plt.annotate("line crossing", (1, -1), (0.8, -0.8), arrowprops={}) # adds both text and arrow; need to set the arrowprops keyword for the arrow to be plotted
``` ```
By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes), By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),
however you can change that. For example to find the middle of the plot in the last example we use however you can change that. For example to find the middle of the plot in the last example we use
...@@ -171,10 +173,10 @@ To prettify this plots, we first need to know what all the features are called: ...@@ -171,10 +173,10 @@ To prettify this plots, we first need to know what all the features are called:
Based on this plot let's figure out what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])` Based on this plot let's figure out what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])`
actually does: actually does:
1. First it creates a figure and makes this the active figure. Being the active figure means that any subsequent commands will affect figure. You can find the active figure at any point by calling `plt.gcf()`. 1. First it creates a figure and makes this the active figure. Being the active figure means that any subsequent commands will affect figure. You can find the active figure at any point by calling `plt.gcf()`.
2. Then it creates an Axes or Subplot in the figure and makes this the active axes. Any subsequent commands will reuse this active axes. You can find the active axes at any point by calling `plt.gca()`. 2. Then it creates an Axes or Subplot in the figure and makes this the active axes. Any subsequent commands will reuse this active axes. You can find the active axes at any point by calling `plt.gca()`.
3. Finally it creates a Line2D artist containing the x-coordinates `[1, 2, 3]` and `[1.3, 4.2, 3.1]` ands adds this to the active axes. 3. Finally it creates a Line2D artist containing the x-coordinates `[1, 2, 3]` and `[1.3, 4.2, 3.1]` ands adds this to the active axes.
4. At some later time, when actually creating the plot, matplotlib will also automatically determine for you a default range for the x-axis and y-axis and where the ticks should be. 4. At some later time, when actually creating the plot, matplotlib will also automatically determine for you a default range for the x-axis and y-axis and where the ticks should be.
This concept of an "active" figure and "active" axes can be very helpful with a single plot, it can quickly get very confusing when you have multiple sub-plots within a figure or even multiple figures. This concept of an "active" figure and "active" axes can be very helpful with a single plot, it can quickly get very confusing when you have multiple sub-plots within a figure or even multiple figures.
In that case we want to be more explicit about what sub-plot we want to add the artist to. In that case we want to be more explicit about what sub-plot we want to add the artist to.
...@@ -219,18 +221,14 @@ The returned `axes` object is in this case a 2x2 array of `Axes` objects, to whi ...@@ -219,18 +221,14 @@ The returned `axes` object is in this case a 2x2 array of `Axes` objects, to whi
> Seaborn is great for creating grids of closely related plots. Before you spent a lot of time implementing your own have a look if seaborn already has what you want on their [gallery](https://seaborn.pydata.org/examples/index.html) > Seaborn is great for creating grids of closely related plots. Before you spent a lot of time implementing your own have a look if seaborn already has what you want on their [gallery](https://seaborn.pydata.org/examples/index.html)
### Adjusting plot layout ### Adjusting plot layout
The default layout of sub-plots is usually good enough, however sometimes you will need some extra space to the plot to accomodate your large axes labels and ticks or you want to get rid of some of the whitespace. The default layout of sub-plots often leads to overlap between the labels/titles of the various subplots (as above) or to excessive amounts of whitespace in between. We can often fix this by just adding `fig.tight_layout` (or `plt.tight_layout`) after making the plot:
``` ```
np.random.seed(1)
fig, axes = plt.subplots(nrows=2, ncols=2) fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat: axes[0, 0].set_title("Upper left")
ax.scatter(np.random.randn(10), np.random.randn(10)) axes[0, 1].set_title("Upper right")
ax.set( axes[1, 0].set_title("Lower left")
title='long multi-\nline title', axes[1, 1].set_title("Lower right")
xlabel='x-label', fig.tight_layout()
ylabel='y-label',
)
#fig.tight_layout()
``` ```
Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace. Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.
If you want more explicit control, you can use `fig.subplots_adjust` (or `plt.subplots_adjust` to do this for the active figure). If you want more explicit control, you can use `fig.subplots_adjust` (or `plt.subplots_adjust` to do this for the active figure).
...@@ -239,10 +237,10 @@ For example, we can remove any whitespace between the plots using: ...@@ -239,10 +237,10 @@ For example, we can remove any whitespace between the plots using:
np.random.seed(1) np.random.seed(1)
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
for ax in axes.flat: for ax in axes.flat:
offset = np.random.rand(2) offset = np.random.rand(2) * 5
ax.scatter(np.random.randn(10) + offset[0], np.random.randn(10) + offset[1]) ax.scatter(np.random.randn(10) + offset[0], np.random.randn(10) + offset[1])
fig.set_suptitle("group of plots, where each row shares the x-axis and each column the y-axis") fig.suptitle("group of plots, sharing x- and y-axes")
fig.subplots_adjust(width=0, height=0, top=0.9) fig.subplots_adjust(wspace=0, hspace=0, top=0.9)
``` ```
### Advanced grid configurations (GridSpec) ### Advanced grid configurations (GridSpec)
...@@ -287,39 +285,39 @@ axes.set( ...@@ -287,39 +285,39 @@ axes.set(
> To match the matlab API and save some typing the equivalent commands in the procedural interface do not have the `set_` preset. So, they are `plt.xlabel`, `plt.ylabel`, `plt.title`. This is also true for many of the `set_` commands we will see below. > To match the matlab API and save some typing the equivalent commands in the procedural interface do not have the `set_` preset. So, they are `plt.xlabel`, `plt.ylabel`, `plt.title`. This is also true for many of the `set_` commands we will see below.
You can edit the font of the text either when setting the label or after the fact. You can edit the font of the text when setting the label:
As an example, here are three ways to change the label colours:
``` ```
fig, axes = plt.subplots() fig, axes = plt.subplots()
axes.plot([1, 2, 3], [2.3, 4.1, 0.8]) axes.plot([1, 2, 3], [2.3, 4.1, 0.8])
axes.set_xlabel("xlabel", color='red') # set color when setting text label axes.set_xlabel("xlabel", color='red')
label = axes.set_ylabel("ylabel") # keep track of the Text object returned by `set_?` axes.set_ylabel("ylabel", fontsize='larger')
label.set_color('blue')
axes.set_title("title")
axes.get_title().set_color('green') # use `get_?` to get the Text object after the fact
``` ```
### Editing the x- and y-axis ### Editing the x- and y-axis
We can change many of the properties of the x- and y-axis by using `set_` commands. We can change many of the properties of the x- and y-axis by using `set_` commands.
- The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`) - The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`)
- You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')` - You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')`
- The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`) - The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`)
- The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`) - The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`)
- The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments). - The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments).
For example: For example:
``` ```
fig, axes = plt.subplots() fig, axes = plt.subplots()
axes.error([0, 1, 2], [0.8, 0.4, -0.2], 0.1, linestyle='0', marker='s') axes.errorbar([0, 1, 2], [0.8, 0.4, -0.2], 0.1, linestyle='-', marker='s')
axes.set_xticks((0, 1, 2)) axes.set_xticks((0, 1, 2))
axes.set_xticklabels(('start', 'middle', 'end')) axes.set_xticklabels(('start', 'middle', 'end'))
for tick in axes.get_ticks(): for tick in axes.get_xticklabels():
tick.set_rotation(45) tick.set(
rotation=45,
size='larger'
)
axes.set_xlabel("Progression through practical") axes.set_xlabel("Progression through practical")
axes.set_yticks((0, 0.5, 1)) axes.set_yticks((0, 0.5, 1))
axes.set_yticklabels(('0', '50%', '100%')) axes.set_yticklabels(('0', '50%', '100%'))
fig.tight_layout()
``` ```
## FAQ ## FAQ
### Why am I getting two images? ### Why am I getting two images?
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment