Skip to content
Snippets Groups Projects
Commit f55e0b1e authored by Sean Fitzgibbon's avatar Sean Fitzgibbon Committed by Paul McCarthy
Browse files

Added example combining matplotlib and nilearn

parent f1a842ea
No related branches found
No related tags found
1 merge request!16Nilearn
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# `nilearn` # `nilearn`
`nilearn` is a python package that provides **statistical** and **machine learning** tools for working with neuroimaging data. `nilearn` is a python package that provides **statistical** and **machine learning** tools for working with neuroimaging data.
According to https://nilearn.github.io/: According to https://nilearn.github.io/:
> >
> Nilearn enables approachable and versatile analyses of brain volumes. It provides **statistical** and **machine-learning** tools, with instructive documentation & open community. > Nilearn enables approachable and versatile analyses of brain volumes. It provides **statistical** and **machine-learning** tools, with instructive documentation & open community.
> >
> It supports general linear model (GLM) based analysis and leverages the scikit-learn Python toolbox for multivariate statistics with applications such as predictive modelling, classification, decoding, or connectivity analysis. > It supports general linear model (GLM) based analysis and leverages the scikit-learn Python toolbox for multivariate statistics with applications such as predictive modelling, classification, decoding, or connectivity analysis.
However, `nilearn` also provides a very convenient set of visualisation routines for neuroimaging data. This notebook will focus on these visualisation tools. However, `nilearn` also provides a very convenient set of visualisation routines for neuroimaging data. This notebook will focus on these visualisation tools.
`nilearn` has very good documentation, and the examples below borrow heavily from the visualisation documentation: https://nilearn.github.io/plotting/index.html `nilearn` has very good documentation, and the examples below borrow heavily from the visualisation documentation: https://nilearn.github.io/plotting/index.html
## This notebook ## This notebook
1. Plotting an anatomical image 1. Plotting an anatomical image
2. Plotting a statistical map 2. Plotting a statistical map
3. 2D maximum intensity projection 3. 2D maximum intensity projection
4. Surfaces 4. Surfaces
Firstly we will import the necessary packages for this notebook: Firstly we will import the necessary packages for this notebook:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import os import os
from nilearn import plotting, datasets, surface from nilearn import plotting, datasets, surface
import matplotlib as mpl import matplotlib as mpl
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import nibabel as nb
%matplotlib inline %matplotlib inline
# get path to FSL installation for the FSLDIR environment variable # get path to FSL installation for the FSLDIR environment variable
FSLDIR = os.environ['FSLDIR'] FSLDIR = os.environ['FSLDIR']
## figure styling ## figure styling
mpl.rcParams['figure.dpi'] = 150 mpl.rcParams['figure.dpi'] = 150
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Plotting an anatomical image ## Plotting an anatomical image
In this section we will use `nilearn` to plot an anatomical volume. For these examples we will use the 1mm MNI152 T1w that is shipped with `FSL`. In these examples you will see differnet plotting layouts, as well as different styling options. In this section we will use `nilearn` to plot an anatomical volume. For these examples we will use the 1mm MNI152 T1w that is shipped with `FSL`. In these examples you will see differnet plotting layouts, as well as different styling options.
First we will use the `plot_anat` function (with default values) to plot the MNI152 T1w in an **ortho** view. First we will use the `plot_anat` function (with default values) to plot the MNI152 T1w in an **ortho** view.
> **NOTE:** > **NOTE:**
> 1. Here we use [`plot_anat`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_anat.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images > 1. Here we use [`plot_anat`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_anat.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images
> 2. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting > 2. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz' f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Here we adjust the brightness of the image using the `dim` argument, and add a title to the plot with the `title` argument. Here we adjust the brightness of the image using the `dim` argument, and add a title to the plot with the `title` argument.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm' title='MNI T1 1mm'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we are going to use the `display_mode` argument to change to a **tiled** ortho view where the coronal and axial views are in a column, and the coronal and sagittal views are in a row. Now we are going to use the `display_mode` argument to change to a **tiled** ortho view where the coronal and axial views are in a column, and the coronal and sagittal views are in a row.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm', title='MNI T1 1mm',
display_mode='tiled' display_mode='tiled'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we are going to combine the `display_mode` and `cut_coords` arguments to create a row of 10 axial slices. Now we are going to combine the `display_mode` and `cut_coords` arguments to create a row of 10 axial slices.
Options for `display_mode` include: Options for `display_mode` include:
- `'x'` - sagittal - `'x'` - sagittal
- `'y'` - coronal - `'y'` - coronal
- `'z'` - axial - `'z'` - axial
- `'ortho'` - three cuts are performed in orthogonal directions - `'ortho'` - three cuts are performed in orthogonal directions
- `'tiled'` - three cuts are performed and arranged in a 2x2 grid - `'tiled'` - three cuts are performed and arranged in a 2x2 grid
In this instance, we give `cut_coords` a scalar integer that indicates the number of slices to show in the axial view. In this instance, we give `cut_coords` a scalar integer that indicates the number of slices to show in the axial view.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_anat( plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm', title='MNI T1 1mm',
display_mode='z', display_mode='z',
cut_coords=10 cut_coords=10
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
In the example below, a `display` object is returned by `plot_anat`. We can use this object to update/amend the plot. Here we add an overlay of the *HarvardOxford* atlas that ships with `FSL` to the image. In the example below, a `display` object is returned by `plot_anat`. We can use this object to update/amend the plot. Here we add an overlay of the *HarvardOxford* atlas that ships with `FSL` to the image.
We also use the `display` object to save the plot as a `*.png` image. We also use the `display` object to save the plot as a `*.png` image.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# plot MNI152 T1w and return display object # plot MNI152 T1w and return display object
display = plotting.plot_anat( display = plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5, dim=-0.5,
title='MNI T1 1mm' title='MNI T1 1mm'
) )
# overlay the HarvardOxford atlas # overlay the HarvardOxford atlas
display.add_contours( display.add_contours(
f'{FSLDIR}/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr50-1mm.nii.gz', f'{FSLDIR}/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr50-1mm.nii.gz',
filled=True filled=True
) )
# save plot to file # save plot to file
display.savefig('myplot.png') display.savefig('myplot.png')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`nilearn` plotting is built upon `matplotlib`, so we can use constructs from `matplotlib` to help us create more complex figures.
In this example we:
1. create a 1x2 grid of subplots using `subplots` from `matplotlib`
2. plot a single slice of the MNI152 T1w in the first subplot using `plot_anat` from `nilearn`
3. plot a histogram of the intensities of the MNI152 T12 in the second subplot using `hist` from `matplotlib`
4. style the histogram by setting the x/y labels
> **NOTE:** Here we use `load` and `get_fdata` from the [`nibabel`](https://nipy.org/nibabel/) package to load the data from the MNI152 T1w nifti for the histogram.
%% Cell type:code id: tags:
``` python
# create matplotlib figure with 1x2 subplots
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
# plot MNI T1w slice in first subplot
mni_t1 = f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
display = plotting.plot_anat(
mni_t1,
dim=-0.5,
axes=ax[0],
display_mode='z',
cut_coords=[15]
)
# plot histogram of MNI T1w intensity in second subplot
mni_t1_data = nb.load(mni_t1).get_fdata().ravel()
ax[1].hist(mni_t1_data, bins=25)
ax[1].set_ylabel('count')
ax[1].set_xlabel('intensity')
```
%% Cell type:markdown id: tags:
> >
> **Exercise:** > **Exercise:**
> >
> Create a PNG figure that displays the same **Harvard-Oxford** parcellation, using a different colormap, and axial images in a 3x5 grid. > Create a PNG figure that displays the same **Harvard-Oxford** parcellation, using a different colormap, and axial images in a 3x5 grid.
> >
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# YOUR CODE HERE # YOUR CODE HERE
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Plotting a statistical map ## Plotting a statistical map
The examples in this section demonstrate how to plot a statistical map as an overlay on an anatomical image. Both images must be in the same space. The examples in this section demonstrate how to plot a statistical map as an overlay on an anatomical image. Both images must be in the same space.
First we will download a motor task statistical map from NeuroVault. First we will download a motor task statistical map from NeuroVault.
> **Note:** We use a method from [`nilearn`](https://nilearn.github.io/index.html) called [`fetch_neurovault_motor_task`](https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_neurovault_motor_task.html) to download the statistical map. > **Note:** We use a method from [`nilearn`](https://nilearn.github.io/index.html) called [`fetch_neurovault_motor_task`](https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_neurovault_motor_task.html) to download the statistical map.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
motor_images = datasets.fetch_neurovault_motor_task() motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0] stat_img = motor_images.images[0]
print(stat_img) print(stat_img)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we can plot the statistical map as an overlay on the MNI152 T1w. We theshold the statistical map using the `threshold` argument. Now we can plot the statistical map as an overlay on the MNI152 T1w. We theshold the statistical map using the `threshold` argument.
> **NOTE:** Here we use [`plot_stat_map`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_stat_map.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images > **NOTE:** Here we use [`plot_stat_map`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_stat_map.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_stat_map( plotting.plot_stat_map(
stat_img, stat_img,
threshold=3, threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz' bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Like with the `plot_anat` examples earlier, we can style the plot and change the layout and views. Like with the `plot_anat` examples earlier, we can style the plot and change the layout and views.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_stat_map( plotting.plot_stat_map(
stat_img, stat_img,
threshold=3, threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
display_mode='z', display_mode='z',
cut_coords=10, cut_coords=10,
title='motor-task', title='motor-task',
dim=-0.5, dim=-0.5,
vmax=10 vmax=10
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
In this next example we first find the coordinate of the centre of the largest connected component in the statistical map, then we plot an ortho view that is centred on this coordinate. In this next example we first find the coordinate of the centre of the largest connected component in the statistical map, then we plot an ortho view that is centred on this coordinate.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# find the coordinate of the centre of the largest connected component in the statistical map # find the coordinate of the centre of the largest connected component in the statistical map
coord = plotting.find_xyz_cut_coords(stat_img) coord = plotting.find_xyz_cut_coords(stat_img)
print(f'Center of the largest activation connected component = {coord}') print(f'Center of the largest activation connected component = {coord}')
# plot an ortho view that is centred on this coordinate # plot an ortho view that is centred on this coordinate
plotting.plot_stat_map( plotting.plot_stat_map(
stat_img, stat_img,
threshold=3, threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
display_mode='ortho', display_mode='ortho',
cut_coords=coord, cut_coords=coord,
title='motor-task', title='motor-task',
dim=-0.5, dim=-0.5,
vmax=10 vmax=10
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`nilearn` has some support for **interactive** viewing of volumetic images with the `view_img` function. Try clicking on the plot and moving the cursor around! `nilearn` has some support for **interactive** viewing of volumetic images with the `view_img` function. Try clicking on the plot and moving the cursor around!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img(stat_img, threshold=3) view = plotting.view_img(stat_img, threshold=3)
view # view interactive plot inline view # view interactive plot inline
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img(stat_img, threshold=3) view = plotting.view_img(stat_img, threshold=3)
view.open_in_browser() # open interactive plot in new web browser view.open_in_browser() # open interactive plot in new web browser
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 2D maximum intensity projection ## 2D maximum intensity projection
> Maximum intensity projection (MIP) is a method for 3D data that projects in the visualization plane the voxels with maximum intensity that fall in the way of parallel rays traced from the viewpoint to the plane of projection. https://en.wikipedia.org/wiki/Maximum_intensity_projection > Maximum intensity projection (MIP) is a method for 3D data that projects in the visualization plane the voxels with maximum intensity that fall in the way of parallel rays traced from the viewpoint to the plane of projection. https://en.wikipedia.org/wiki/Maximum_intensity_projection
`nilearn` can plot a maximum intensity projection overlayed on a brain schematic referred to as the "glass brain". In this example, the MIP of the motor task statistical map used in the previous examples is plotted on the glass brain. `nilearn` can plot a maximum intensity projection overlayed on a brain schematic referred to as the "glass brain". In this example, the MIP of the motor task statistical map used in the previous examples is plotted on the glass brain.
> **NOTE:** Here we use [`plot_glass_brain`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_glass_brain.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the maximum intensity projection. > **NOTE:** Here we use [`plot_glass_brain`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_glass_brain.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the maximum intensity projection.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_glass_brain( plotting.plot_glass_brain(
stat_img, stat_img,
title='2D max-intensity projection', title='2D max-intensity projection',
threshold=3, threshold=3,
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Surfaces ## Surfaces
`nilearn` has baked in functionality to project a volumetric image onto the surface and visualise it. `nilearn` has baked in functionality to project a volumetric image onto the surface and visualise it.
Here we visualise the same volumetric motor task statistical map, from earlier examples, on the inflated surface. Here we visualise the same volumetric motor task statistical map, from earlier examples, on the inflated surface.
> **NOTE:** Here we use [`plot_img_on_surf`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_img_on_surf.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the volumetric statistical map on the surface. > **NOTE:** Here we use [`plot_img_on_surf`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_img_on_surf.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the volumetric statistical map on the surface.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plotting.plot_img_on_surf( plotting.plot_img_on_surf(
stat_img, stat_img,
inflate=True, inflate=True,
threshold=0.5, threshold=0.5,
vmax=6 vmax=6
); );
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`nilearn` also has some support for **interactive** viewing of volumetic images on the surface with the `view_img_on_surf` function. Try clicking on the plot and moving the cursor around! `nilearn` also has some support for **interactive** viewing of volumetic images on the surface with the `view_img_on_surf` function. Try clicking on the plot and moving the cursor around!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img_on_surf( view = plotting.view_img_on_surf(
stat_img, stat_img,
threshold=0.5, threshold=0.5,
surf_mesh='fsaverage', surf_mesh='fsaverage',
vmax=6 vmax=6
) )
view # view interactive plot inline view # view interactive plot inline
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
view = plotting.view_img_on_surf( view = plotting.view_img_on_surf(
stat_img, stat_img,
threshold=0.5, threshold=0.5,
surf_mesh='fsaverage', surf_mesh='fsaverage',
vmax=6 vmax=6
) )
view.open_in_browser() # view interactive plot inline view.open_in_browser() # view interactive plot inline
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
> >
> **Exercise:** > **Exercise:**
> >
> Visualise thee **Harvard-Oxford** atlas on a surface in the weeb Browser > Visualise thee **Harvard-Oxford** atlas on a surface in the web browser
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# YOUR CODE HERE # YOUR CODE HERE
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
That's all folks.... That's all folks....
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment