Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
P
pytreat-practicals-2020
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Container Registry
Model registry
Operate
Environments
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
FSL
pytreat-practicals-2020
Commits
a52df4ab
Commit
a52df4ab
authored
7 years ago
by
Mark Jenkinson
Browse files
Options
Downloads
Patches
Plain Diff
New practical on plotting
parent
a2d20a4d
No related branches found
Branches containing commit
No related tags found
No related merge requests found
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
getting_started/06_plotting.ipynb
+228
-0
228 additions, 0 deletions
getting_started/06_plotting.ipynb
getting_started/06_plotting.md
+135
-0
135 additions, 0 deletions
getting_started/06_plotting.md
with
363 additions
and
0 deletions
getting_started/06_plotting.ipynb
0 → 100644
+
228
−
0
View file @
a52df4ab
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Plotting with python\n",
"\n",
"The main plotting module in python is `matplotlib`. There is a lot\n",
"that can be done with it - see the [webpage](https://matplotlib.org/gallery/index.html)\n",
"\n",
"## Inside a notebook\n",
"\n",
"Inside a jupyter notebook you get access to this in a slightly\n",
"different way, compared to other modules:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This only needs to be done once in a notebook, like for standard imports.\n",
"\n",
"> There are also interactive versions - see the practical on Jupyter notebooks for more information about this.\n",
"\n",
"\n",
"The library works very similarly to plotting in matlab. Let's start\n",
"with some simple examples.\n",
"\n",
"### 2D plots"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"x = np.linspace(-np.pi, np.pi, 256)\n",
"cosx, sinx = np.cos(x), np.sin(x)\n",
"\n",
"plt.plot(x, cosx)\n",
"plt.plot(x, sinx, color='red', linewidth=4, linestyle='-.')\n",
"plt.plot(x, sinx**2)\n",
"plt.xlim(-np.pi, np.pi)\n",
"plt.title('Our first plots')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Histograms and bar charts\n",
"\n",
"For a simple histogram you can do this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"r = np.random.rand(1000)\n",
"n,bins,_ = plt.hist((r-0.5)**2, bins=30)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where it also returns the number of elements in each bin, as `n`, and\n",
"the bin centres, as `bins`. The `_` in the third part on the left\n",
"hand side is a shorthand for just throwing away the corresponding part\n",
"of the return structure.\n",
"\n",
"\n",
"There is also a call for doing bar plots:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"samp1 = r[0:10]\n",
"samp2 = r[10:20]\n",
"bwidth = 0.3\n",
"xcoord = np.arange(10)\n",
"ax.bar(xcoord-bwidth, samp1, width=bwidth, color='red', label='Sample 1')\n",
"ax.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2')\n",
"ax.legend(loc='upper left')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the first line returns a handle to the axis, as `ax`, that\n",
"we can use instead of `plt`\n",
"\n",
"### Scatter plots"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots()\n",
"ssize = 100*abs(samp1-samp2) # just an arbitrary example\n",
"ax.scatter(samp1, samp2, s=ssize, alpha=0.5)\n",
"allsamps = np.hstack((samp1,samp2))\n",
"ax.plot([min(allsamps),max(allsamps)],[min(allsamps),max(allsamps)], color='red', linestyle='--')\n",
"plt.xlim(min(allsamps),max(allsamps))\n",
"plt.ylim(min(allsamps),max(allsamps))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Subplots"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.subplot(2, 1, 1)\n",
"plt.plot(x,cosx, '.-')\n",
"plt.xlim(-np.pi, np.pi)\n",
"plt.ylabel('Full sampling')\n",
"plt.subplot(2, 1, 2)\n",
"plt.plot(x[::30], cosx[::30], '.-')\n",
"plt.xlim(-np.pi, np.pi)\n",
"plt.ylabel('Subsampled')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Displaying images"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import nibabel as nib\n",
"import os.path as op\n",
"nim = nib.load(op.expandvars('${FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'), mmap=False)\n",
"imdat = nim.get_data().astype(float)\n",
"plt.imshow(imdat[:,:,70], cmap=plt.cm.gray)\n",
"plt.colorbar()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3D plots"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Taken from https://matplotlib.org/gallery/mplot3d/wire3d.html#sphx-glr-gallery-mplot3d-wire3d-py\n",
"\n",
"from mpl_toolkits.mplot3d import axes3d\n",
"\n",
"fig = plt.figure()\n",
"ax = fig.add_subplot(111, projection='3d')\n",
"\n",
"# Grab some test data.\n",
"X, Y, Z = axes3d.get_test_data(0.05)\n",
"\n",
"# Plot a basic wireframe.\n",
"ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Surface renderings are many other plots are possible - see 3D examples on\n",
"the [matplotlib webpage](https://matplotlib.org/gallery/index.html#mplot3d-examples-index)\n",
"\n",
"## Plotting from standalone scripts\n",
"\n",
"When running from a standalone script, the same `matplotlib` import is required,\n",
"but the line `%matplotlib <backend>` should *not* be used.\n",
"\n",
"In a script it is necessary to also _finish_ with `plt.show()` as\n",
"otherwise nothing is actually displayed. For example, the above\n",
"examples would setup a plot but the actual graphic would only appear\n",
"after the `plt.show()` command was executed. Furthermore, control is\n",
"not returned to the script immediately as the plot is interactive by default."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
%% Cell type:markdown id: tags:
# Plotting with python
The main plotting module in python is
`matplotlib`
. There is a lot
that can be done with it - see the
[
webpage
](
https://matplotlib.org/gallery/index.html
)
## Inside a notebook
Inside a jupyter notebook you get access to this in a slightly
different way, compared to other modules:
%% Cell type:code id: tags:
```
%matplotlib inline
```
%% Cell type:markdown id: tags:
This only needs to be done once in a notebook, like for standard imports.
> There are also interactive versions - see the practical on Jupyter notebooks for more information about this.
The library works very similarly to plotting in matlab. Let's start
with some simple examples.
### 2D plots
%% Cell type:code id: tags:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi, np.pi, 256)
cosx, sinx = np.cos(x), np.sin(x)
plt.plot(x, cosx)
plt.plot(x, sinx, color='red', linewidth=4, linestyle='-.')
plt.plot(x, sinx**2)
plt.xlim(-np.pi, np.pi)
plt.title('Our first plots')
```
%% Cell type:markdown id: tags:
### Histograms and bar charts
For a simple histogram you can do this:
%% Cell type:code id: tags:
```
r = np.random.rand(1000)
n,bins,_ = plt.hist((r-0.5)**2, bins=30)
```
%% Cell type:markdown id: tags:
where it also returns the number of elements in each bin, as
`n`
, and
the bin centres, as
`bins`
. The
`_`
in the third part on the left
hand side is a shorthand for just throwing away the corresponding part
of the return structure.
There is also a call for doing bar plots:
%% Cell type:code id: tags:
```
fig, ax = plt.subplots()
samp1 = r[0:10]
samp2 = r[10:20]
bwidth = 0.3
xcoord = np.arange(10)
ax.bar(xcoord-bwidth, samp1, width=bwidth, color='red', label='Sample 1')
ax.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2')
ax.legend(loc='upper left')
```
%% Cell type:markdown id: tags:
Note that the first line returns a handle to the axis, as
`ax`
, that
we can use instead of
`plt`
### Scatter plots
%% Cell type:code id: tags:
```
fig, ax = plt.subplots()
ssize = 100*abs(samp1-samp2) # just an arbitrary example
ax.scatter(samp1, samp2, s=ssize, alpha=0.5)
allsamps = np.hstack((samp1,samp2))
ax.plot([min(allsamps),max(allsamps)],[min(allsamps),max(allsamps)], color='red', linestyle='--')
plt.xlim(min(allsamps),max(allsamps))
plt.ylim(min(allsamps),max(allsamps))
```
%% Cell type:markdown id: tags:
### Subplots
%% Cell type:code id: tags:
```
plt.subplot(2, 1, 1)
plt.plot(x,cosx, '.-')
plt.xlim(-np.pi, np.pi)
plt.ylabel('Full sampling')
plt.subplot(2, 1, 2)
plt.plot(x[::30], cosx[::30], '.-')
plt.xlim(-np.pi, np.pi)
plt.ylabel('Subsampled')
```
%% Cell type:markdown id: tags:
### Displaying images
%% Cell type:code id: tags:
```
import nibabel as nib
import os.path as op
nim = nib.load(op.expandvars('${FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'), mmap=False)
imdat = nim.get_data().astype(float)
plt.imshow(imdat[:,:,70], cmap=plt.cm.gray)
plt.colorbar()
```
%% Cell type:markdown id: tags:
### 3D plots
%% Cell type:code id: tags:
```
# Taken from https://matplotlib.org/gallery/mplot3d/wire3d.html#sphx-glr-gallery-mplot3d-wire3d-py
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)
# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
```
%% Cell type:markdown id: tags:
Surface renderings are many other plots are possible - see 3D examples on
the
[
matplotlib webpage
](
https://matplotlib.org/gallery/index.html#mplot3d-examples-index
)
## Plotting from standalone scripts
When running from a standalone script, the same
`matplotlib`
import is required,
but the line
`%matplotlib <backend>`
should
*not*
be used.
In a script it is necessary to also _finish_ with
`plt.show()`
as
otherwise nothing is actually displayed. For example, the above
examples would setup a plot but the actual graphic would only appear
after the
`plt.show()`
command was executed. Furthermore, control is
not returned to the script immediately as the plot is interactive by default.
This diff is collapsed.
Click to expand it.
getting_started/06_plotting.md
0 → 100644
+
135
−
0
View file @
a52df4ab
# Plotting with python
The main plotting module in python is
`matplotlib`
. There is a lot
that can be done with it - see the
[
webpage
](
https://matplotlib.org/gallery/index.html
)
## Inside a notebook
Inside a jupyter notebook you get access to this in a slightly
different way, compared to other modules:
```
%matplotlib inline
```
This only needs to be done once in a notebook, like for standard imports.
> There are also interactive versions - see the practical on Jupyter notebooks for more information about this.
The library works very similarly to plotting in matlab. Let's start
with some simple examples.
### 2D plots
```
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi, np.pi, 256)
cosx, sinx = np.cos(x), np.sin(x)
plt.plot(x, cosx)
plt.plot(x, sinx, color='red', linewidth=4, linestyle='-.')
plt.plot(x, sinx**2)
plt.xlim(-np.pi, np.pi)
plt.title('Our first plots')
```
### Histograms and bar charts
For a simple histogram you can do this:
```
r = np.random.rand(1000)
n,bins,_ = plt.hist((r-0.5)**2, bins=30)
```
where it also returns the number of elements in each bin, as
`n`
, and
the bin centres, as
`bins`
. The
`_`
in the third part on the left
hand side is a shorthand for just throwing away the corresponding part
of the return structure.
There is also a call for doing bar plots:
```
fig, ax = plt.subplots()
samp1 = r[0:10]
samp2 = r[10:20]
bwidth = 0.3
xcoord = np.arange(10)
ax.bar(xcoord-bwidth, samp1, width=bwidth, color='red', label='Sample 1')
ax.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2')
ax.legend(loc='upper left')
```
Note that the first line returns a handle to the axis, as
`ax`
, that
we can use instead of
`plt`
### Scatter plots
```
fig, ax = plt.subplots()
ssize = 100*abs(samp1-samp2) # just an arbitrary example
ax.scatter(samp1, samp2, s=ssize, alpha=0.5)
allsamps = np.hstack((samp1,samp2))
ax.plot([min(allsamps),max(allsamps)],[min(allsamps),max(allsamps)], color='red', linestyle='--')
plt.xlim(min(allsamps),max(allsamps))
plt.ylim(min(allsamps),max(allsamps))
```
### Subplots
```
plt.subplot(2, 1, 1)
plt.plot(x,cosx, '.-')
plt.xlim(-np.pi, np.pi)
plt.ylabel('Full sampling')
plt.subplot(2, 1, 2)
plt.plot(x[::30], cosx[::30], '.-')
plt.xlim(-np.pi, np.pi)
plt.ylabel('Subsampled')
```
### Displaying images
```
import nibabel as nib
import os.path as op
nim = nib.load(op.expandvars('${FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'), mmap=False)
imdat = nim.get_data().astype(float)
plt.imshow(imdat[:,:,70], cmap=plt.cm.gray)
plt.colorbar()
```
### 3D plots
```
# Taken from https://matplotlib.org/gallery/mplot3d/wire3d.html#sphx-glr-gallery-mplot3d-wire3d-py
from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)
# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
```
Surface renderings are many other plots are possible - see 3D examples on
the
[
matplotlib webpage
](
https://matplotlib.org/gallery/index.html#mplot3d-examples-index
)
## Plotting from standalone scripts
When running from a standalone script, the same
`matplotlib`
import is required,
but the line
`%matplotlib <backend>`
should
*not*
be used.
In a script it is necessary to also _finish_ with
`plt.show()`
as
otherwise nothing is actually displayed. For example, the above
examples would setup a plot but the actual graphic would only appear
after the
`plt.show()`
command was executed. Furthermore, control is
not returned to the script immediately as the plot is interactive by default.
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment