/
_slicers.py
1924 lines (1598 loc) · 70 KB
/
_slicers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numbers
import collections
from nilearn._utils.docs import fill_doc
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
from matplotlib.colorbar import ColorbarBase
from matplotlib.transforms import Bbox
from nilearn.version import _compare_version
from nilearn._utils import check_niimg_3d
from nilearn.plotting.find_cuts import find_xyz_cut_coords, find_cut_slices
from nilearn.plotting.displays import CutAxes
from nilearn.plotting.edge_detect import _edge_map
from nilearn.image.resampling import get_bounds, get_mask_bounds
from nilearn.image import reorder_img, new_img_like, get_data
from nilearn._utils.niimg import _is_binary_niimg, _safe_get_data
from nilearn.plotting.displays._axes import _coords_3d_to_2d
class BaseSlicer:
"""BaseSlicer implementation which main purpose is to auto adjust
the axes size to the data with different layout of cuts. It create
3 linked axes for plotting orthogonal cuts.
Attributes
----------
cut_coords : 3 :obj:`tuple` of :obj:`int`
The cut position, in world space.
frame_axes : :class:`matplotlib.axes.Axes`, optional
The matplotlib axes that will be subdivided in 3.
black_bg : :obj:`bool`, optional
If ``True``, the background of the figure will be put to
black. If you wish to save figures with a black background,
you will need to pass ``facecolor='k', edgecolor='k'``
to :func:`~matplotlib.pyplot.savefig`.
Default=False.
brain_color : :obj:`tuple`, optional
The brain color to use as the background color (e.g., for
transparent colorbars).
Default=(0.5, 0.5, 0.5)
"""
# This actually encodes the figsize for only one axe
_default_figsize = [2.2, 2.6]
_axes_class = CutAxes
def __init__(self, cut_coords, axes=None, black_bg=False,
brain_color=(0.5, 0.5, 0.5), **kwargs):
self.cut_coords = cut_coords
if axes is None:
axes = plt.axes((0., 0., 1., 1.))
axes.axis('off')
self.frame_axes = axes
axes.set_zorder(1)
bb = axes.get_position()
self.rect = (bb.x0, bb.y0, bb.x1, bb.y1)
self._black_bg = black_bg
self._brain_color = brain_color
self._colorbar = False
self._colorbar_width = 0.05 * bb.width
self._cbar_tick_format = "%.2g"
self._colorbar_margin = dict(left=0.25 * bb.width,
right=0.02 * bb.width,
top=0.05 * bb.height,
bottom=0.05 * bb.height)
self._init_axes(**kwargs)
@property
def brain_color(self):
return self._brain_color
@property
def black_bg(self):
return self._black_bg
@staticmethod
def find_cut_coords(img=None, threshold=None, cut_coords=None):
"""This is not implemented in the base class and has to
be implemented in derived classes.
"""
# Implement this as a staticmethod or a classmethod when
# subclassing
raise NotImplementedError
@classmethod
@fill_doc
def init_with_figure(cls, img, threshold=None,
cut_coords=None, figure=None, axes=None,
black_bg=False, leave_space=False, colorbar=False,
brain_color=(0.5, 0.5, 0.5), **kwargs):
"""Initialize the slicer with an image.
Parameters
----------
%(img)s
cut_coords : 3 :obj:`tuple` of :obj:`int`
The cut position, in world space.
axes : :class:`matplotlib.axes.Axes`, optional
The axes that will be subdivided in 3.
black_bg : :obj:`bool`, optional
If ``True``, the background of the figure will be put to
black. If you wish to save figures with a black background,
you will need to pass ``facecolor='k', edgecolor='k'``
to :func:`matplotlib.pyplot.savefig`.
Default=False.
brain_color : :obj:`tuple`, optional
The brain color to use as the background color (e.g., for
transparent colorbars).
Default=(0.5, 0.5, 0.5).
"""
# deal with "fake" 4D images
if img is not None and img is not False:
img = check_niimg_3d(img)
cut_coords = cls.find_cut_coords(img, threshold, cut_coords)
if isinstance(axes, plt.Axes) and figure is None:
figure = axes.figure
if not isinstance(figure, plt.Figure):
# Make sure that we have a figure
figsize = cls._default_figsize[:]
# Adjust for the number of axes
figsize[0] *= len(cut_coords)
# Make space for the colorbar
if colorbar:
figsize[0] += .7
facecolor = 'k' if black_bg else 'w'
if leave_space:
figsize[0] += 3.4
figure = plt.figure(figure, figsize=figsize,
facecolor=facecolor)
if isinstance(axes, plt.Axes):
assert axes.figure is figure, ("The axes passed are not "
"in the figure")
if axes is None:
axes = [0., 0., 1., 1.]
if leave_space:
axes = [0.3, 0, .7, 1.]
if isinstance(axes, collections.abc.Sequence):
axes = figure.add_axes(axes)
# People forget to turn their axis off, or to set the zorder, and
# then they cannot see their slicer
axes.axis('off')
return cls(cut_coords, axes, black_bg, brain_color, **kwargs)
def title(self, text, x=0.01, y=0.99, size=15, color=None, bgcolor=None,
alpha=1, **kwargs):
"""Write a title to the view.
Parameters
----------
text : :obj:`str`
The text of the title.
x : :obj:`float`, optional
The horizontal position of the title on the frame in
fraction of the frame width. Default=0.01.
y : :obj:`float`, optional
The vertical position of the title on the frame in
fraction of the frame height. Default=0.99.
size : :obj:`int`, optional
The size of the title text. Default=15.
color : matplotlib color specifier, optional
The color of the font of the title.
bgcolor : matplotlib color specifier, optional
The color of the background of the title.
alpha : :obj:`float`, optional
The alpha value for the background. Default=1.
kwargs :
Extra keyword arguments are passed to matplotlib's text
function.
"""
if color is None:
color = 'k' if self._black_bg else 'w'
if bgcolor is None:
bgcolor = 'w' if self._black_bg else 'k'
if hasattr(self, '_cut_displayed'):
# Adapt to the case of mosaic plotting
if isinstance(self.cut_coords, dict):
first_axe = self._cut_displayed[-1]
first_axe = (first_axe, self.cut_coords[first_axe][0])
else:
first_axe = self._cut_displayed[0]
else:
first_axe = self.cut_coords[0]
ax = self.axes[first_axe].ax
ax.text(x, y, text,
transform=self.frame_axes.transAxes,
horizontalalignment='left',
verticalalignment='top',
size=size, color=color,
bbox=dict(boxstyle="square,pad=.3",
ec=bgcolor, fc=bgcolor, alpha=alpha),
zorder=1000,
**kwargs)
ax.set_zorder(1000)
@fill_doc
def add_overlay(self, img, threshold=1e-6, colorbar=False,
cbar_tick_format="%.2g", cbar_vmin=None, cbar_vmax=None,
**kwargs):
""" Plot a 3D map in all the views.
Parameters
----------
%(img)s
If it is a masked array, only the non-masked part will be plotted.
threshold : :obj:`int` or :obj:`float` or ``None``, optional
Threshold to apply:
- If ``None`` is given, the maps are not thresholded.
- If a number is given, it is used to threshold the maps:
values below the threshold (in absolute value) are
plotted as transparent.
Default=1e-6.
cbar_tick_format: str, optional
Controls how to format the tick labels of the colorbar.
Ex: use "%%i" to display as integers.
Default is '%%.2g' for scientific notation.
colorbar : :obj:`bool`, optional
If ``True``, display a colorbar on the right of the plots.
Default=False.
kwargs : :obj:`dict`
Extra keyword arguments are passed to function
:func:`~matplotlib.pyplot.imshow`.
cbar_vmin : :obj:`float`, optional
Minimal value for the colorbar. If None, the minimal value
is computed based on the data.
cbar_vmax : :obj:`float`, optional
Maximal value for the colorbar. If None, the maximal value
is computed based on the data.
"""
if colorbar and self._colorbar:
raise ValueError("This figure already has an overlay with a "
"colorbar.")
else:
self._colorbar = colorbar
self._cbar_tick_format = cbar_tick_format
img = check_niimg_3d(img)
# Make sure that add_overlay shows consistent default behavior
# with plot_stat_map
kwargs.setdefault('interpolation', 'nearest')
ims = self._map_show(img, type='imshow', threshold=threshold, **kwargs)
# `ims` can be empty in some corner cases, look at test_img_plotting.test_outlier_cut_coords.
if colorbar and ims:
self._show_colorbar(ims[0].cmap, ims[0].norm,
cbar_vmin, cbar_vmax, threshold)
plt.draw_if_interactive()
@fill_doc
def add_contours(self, img, threshold=1e-6, filled=False, **kwargs):
""" Contour a 3D map in all the views.
Parameters
----------
%(img)s
Provides image to plot.
threshold : :obj:`int` or :obj:`float` or ``None``, optional
Threshold to apply:
- If ``None`` is given, the maps are not thresholded.
- If a number is given, it is used to threshold the maps,
values below the threshold (in absolute value) are plotted
as transparent.
Default=1e-6.
filled : :obj:`bool`, optional
If ``filled=True``, contours are displayed with color fillings.
Default=False.
kwargs : :obj:`dict`
Extra keyword arguments are passed to function
:func:`~matplotlib.pyplot.contour`, or function
:func:`~matplotlib.pyplot.contourf`.
Useful, arguments are typical "levels", which is a
list of values to use for plotting a contour or contour
fillings (if ``filled=True``), and
"colors", which is one color or a list of colors for
these contours.
Notes
-----
If colors are not specified, default coloring choices
(from matplotlib) for contours and contour_fillings can be
different.
"""
if not filled:
threshold = None
self._map_show(img, type='contour', threshold=threshold, **kwargs)
if filled:
if 'levels' in kwargs:
levels = kwargs['levels']
if len(levels) <= 1:
# contour fillings levels should be given as (lower, upper).
levels.append(np.inf)
self._map_show(img, type='contourf', threshold=threshold, **kwargs)
plt.draw_if_interactive()
def _map_show(self, img, type='imshow',
resampling_interpolation='continuous',
threshold=None, **kwargs):
# In the special case where the affine of img is not diagonal,
# the function `reorder_img` will trigger a resampling
# of the provided image with a continuous interpolation
# since this is the default value here. In the special
# case where this image is binary, such as when this function
# is called from `add_contours`, continuous interpolation
# does not make sense and we turn to nearest interpolation instead.
if _is_binary_niimg(img):
img = reorder_img(img, resample='nearest')
else:
img = reorder_img(img, resample=resampling_interpolation)
threshold = float(threshold) if threshold is not None else None
if threshold is not None:
data = _safe_get_data(img, ensure_finite=True)
if threshold == 0:
data = np.ma.masked_equal(data, 0, copy=False)
else:
data = np.ma.masked_inside(data, -threshold, threshold,
copy=False)
img = new_img_like(img, data, img.affine)
affine = img.affine
data = _safe_get_data(img, ensure_finite=True)
data_bounds = get_bounds(data.shape, affine)
(xmin, xmax), (ymin, ymax), (zmin, zmax) = data_bounds
xmin_, xmax_, ymin_, ymax_, zmin_, zmax_ = \
xmin, xmax, ymin, ymax, zmin, zmax
# Compute tight bounds
if type in ('contour', 'contourf'):
# Define a pseudo threshold to have a tight bounding box
if 'levels' in kwargs:
thr = 0.9 * np.min(np.abs(kwargs['levels']))
else:
thr = 1e-6
not_mask = np.logical_or(data > thr, data < -thr)
xmin_, xmax_, ymin_, ymax_, zmin_, zmax_ = \
get_mask_bounds(new_img_like(img, not_mask, affine))
elif hasattr(data, 'mask') and isinstance(data.mask, np.ndarray):
not_mask = np.logical_not(data.mask)
xmin_, xmax_, ymin_, ymax_, zmin_, zmax_ = \
get_mask_bounds(new_img_like(img, not_mask, affine))
data_2d_list = []
for display_ax in self.axes.values():
try:
data_2d = display_ax.transform_to_2d(data, affine)
except IndexError:
# We are cutting outside the indices of the data
data_2d = None
data_2d_list.append(data_2d)
if kwargs.get('vmin') is None:
kwargs['vmin'] = np.ma.min([d.min() for d in data_2d_list
if d is not None])
if kwargs.get('vmax') is None:
kwargs['vmax'] = np.ma.max([d.max() for d in data_2d_list
if d is not None])
bounding_box = (xmin_, xmax_), (ymin_, ymax_), (zmin_, zmax_)
ims = []
to_iterate_over = zip(self.axes.values(), data_2d_list)
for display_ax, data_2d in to_iterate_over:
if data_2d is not None and data_2d.min() is not np.ma.masked:
# If data_2d is completely masked, then there is nothing to
# plot. Hence, no point to do imshow(). Moreover, we see
# problem came up with matplotlib 2.1.0 (issue #9280) when
# data is completely masked or with numpy < 1.14
# (issue #4595). This work around can be removed when bumping
# matplotlib version above 2.1.0
im = display_ax.draw_2d(data_2d, data_bounds, bounding_box,
type=type, **kwargs)
ims.append(im)
return ims
@fill_doc
def _show_colorbar(self, cmap, norm, cbar_vmin=None,
cbar_vmax=None, threshold=None):
"""Displays the colorbar.
Parameters
----------
%(cmap)s
norm : :class:`~matplotlib.colors.Normalize`
This object is typically found as the ``norm`` attribute of
:class:`~matplotlib.image.AxesImage`.
threshold : :obj:`float` or ``None``, optional
The absolute value at which the colorbar is thresholded.
cbar_vmin : :obj:`float`, optional
Minimal value for the colorbar. If None, the minimal value
is computed based on the data.
cbar_vmax : :obj:`float`, optional
Maximal value for the colorbar. If None, the maximal value
is computed based on the data.
"""
if threshold is None:
offset = 0
else:
offset = threshold
if offset > norm.vmax:
offset = norm.vmax
cbar_vmin = cbar_vmin if cbar_vmin is not None else norm.vmin
cbar_vmax = cbar_vmax if cbar_vmax is not None else norm.vmax
# create new axis for the colorbar
figure = self.frame_axes.figure
_, y0, x1, y1 = self.rect
height = y1 - y0
x_adjusted_width = self._colorbar_width / len(self.axes)
x_adjusted_margin = self._colorbar_margin['right'] / len(self.axes)
lt_wid_top_ht = [x1 - (x_adjusted_width + x_adjusted_margin),
y0 + self._colorbar_margin['top'],
x_adjusted_width,
height - (self._colorbar_margin['top'] +
self._colorbar_margin['bottom'])]
self._colorbar_ax = figure.add_axes(lt_wid_top_ht)
if _compare_version(matplotlib.__version__, '>=', "1.6"):
self._colorbar_ax.set_facecolor('w')
else:
self._colorbar_ax.set_axis_bgcolor('w')
our_cmap = plt.get_cmap(cmap)
# edge case where the data has a single value
# yields a cryptic matplotlib error message
# when trying to plot the color bar
nb_ticks = 5 if cbar_vmin != cbar_vmax else 1
ticks = np.linspace(cbar_vmin, cbar_vmax, nb_ticks)
bounds = np.linspace(cbar_vmin, cbar_vmax, our_cmap.N)
# some colormap hacking
cmaplist = [our_cmap(i) for i in range(our_cmap.N)]
transparent_start = int(norm(-offset, clip=True) * (our_cmap.N - 1))
transparent_stop = int(norm(offset, clip=True) * (our_cmap.N - 1))
for i in range(transparent_start, transparent_stop):
cmaplist[i] = self._brain_color + (0.,) # transparent
if cbar_vmin == cbar_vmax: # len(np.unique(data)) == 1 ?
return
else:
our_cmap = LinearSegmentedColormap.from_list(
'Custom cmap', cmaplist, our_cmap.N
)
self._cbar = ColorbarBase(
self._colorbar_ax, ticks=ticks, norm=norm,
orientation='vertical', cmap=our_cmap, boundaries=bounds,
spacing='proportional', format=self._cbar_tick_format)
self._cbar.ax.set_facecolor(self._brain_color)
self._colorbar_ax.yaxis.tick_left()
tick_color = 'w' if self._black_bg else 'k'
outline_color = 'w' if self._black_bg else 'k'
for tick in self._colorbar_ax.yaxis.get_ticklabels():
tick.set_color(tick_color)
self._colorbar_ax.yaxis.set_tick_params(width=0)
self._cbar.outline.set_edgecolor(outline_color)
@fill_doc
def add_edges(self, img, color='r'):
"""Plot the edges of a 3D map in all the views.
Parameters
----------
%(img)s
The 3D map to be plotted.
If it is a masked array, only the non-masked part will be plotted.
color : matplotlib color: :obj:`str` or (r, g, b) value
The color used to display the edge map.
Default='r'.
"""
img = reorder_img(img, resample='continuous')
data = get_data(img)
affine = img.affine
single_color_cmap = ListedColormap([color])
data_bounds = get_bounds(data.shape, img.affine)
# For each ax, cut the data and plot it
for display_ax in self.axes.values():
try:
data_2d = display_ax.transform_to_2d(data, affine)
edge_mask = _edge_map(data_2d)
except IndexError:
# We are cutting outside the indices of the data
continue
display_ax.draw_2d(edge_mask, data_bounds, data_bounds,
type='imshow', cmap=single_color_cmap)
plt.draw_if_interactive()
def add_markers(self, marker_coords, marker_color='r', marker_size=30,
**kwargs):
"""Add markers to the plot.
Parameters
----------
marker_coords : :class:`~numpy.ndarray` of shape ``(n_markers, 3)``
Coordinates of the markers to plot. For each slice, only markers
that are 2 millimeters away from the slice are plotted.
marker_color : pyplot compatible color or :obj:`list` of\
shape ``(n_markers,)``, optional
List of colors for each marker that can be string or matplotlib colors.
Default='r'.
marker_size : :obj:`float` or :obj:`list` of :obj:`float` of\
shape ``(n_markers,)``, optional
Size in pixel for each marker. Default=30.
"""
defaults = {'marker': 'o',
'zorder': 1000}
marker_coords = np.asanyarray(marker_coords)
for k, v in defaults.items():
kwargs.setdefault(k, v)
for display_ax in self.axes.values():
direction = display_ax.direction
coord = display_ax.coord
marker_coords_2d, third_d = _coords_3d_to_2d(
marker_coords, direction, return_direction=True)
xdata, ydata = marker_coords_2d.T
# Allow markers only in their respective hemisphere when appropriate
marker_color_ = marker_color
marker_size_ = marker_size
if direction in ('lr'):
if (not isinstance(marker_color, str) and
not isinstance(marker_color, np.ndarray)):
marker_color_ = np.asarray(marker_color)
xcoords, ycoords, zcoords = marker_coords.T
if direction == 'r':
relevant_coords = (xcoords >= 0)
elif direction == 'l':
relevant_coords = (xcoords <= 0)
xdata = xdata[relevant_coords]
ydata = ydata[relevant_coords]
if (not isinstance(marker_color, str) and
len(marker_color) != 1):
marker_color_ = marker_color_[relevant_coords]
if not isinstance(marker_size, numbers.Number):
marker_size_ = np.asarray(marker_size_)[relevant_coords]
# Check if coord has integer represents a cut in direction
# to follow the heuristic. If no foreground image is given
# coordinate is empty or None. This case is valid for plotting
# markers on glass brain without any foreground image.
if isinstance(coord, numbers.Number):
# Heuristic that plots only markers that are 2mm away
# from the current slice.
# XXX: should we keep this heuristic?
mask = np.abs(third_d - coord) <= 2.
xdata = xdata[mask]
ydata = ydata[mask]
display_ax.ax.scatter(xdata, ydata, s=marker_size_,
c=marker_color_, **kwargs)
def annotate(self, left_right=True, positions=True, scalebar=False,
size=12, scale_size=5.0, scale_units='cm', scale_loc=4,
decimals=0, **kwargs):
"""Add annotations to the plot.
Parameters
----------
left_right : :obj:`bool`, optional
If ``True``, annotations indicating which side
is left and which side is right are drawn.
Default=True.
positions : :obj:`bool`, optional
If ``True``, annotations indicating the
positions of the cuts are drawn.
Default=True.
scalebar : :obj:`bool`, optional
If ``True``, cuts are annotated with a reference scale bar.
For finer control of the scale bar, please check out
the ``draw_scale_bar`` method on the axes in "axes" attribute
of this object.
Default=False.
size : :obj:`int`, optional
The size of the text used. Default=12.
scale_size : :obj:`int` or :obj:`float`, optional
The length of the scalebar, in units of ``scale_units``.
Default=5.0.
scale_units : {'cm', 'mm'}, optional
The units for the ``scalebar``. Default='cm'.
scale_loc : :obj:`int`, optional
The positioning for the scalebar. Default=4.
Valid location codes are:
- 1: "upper right"
- 2: "upper left"
- 3: "lower left"
- 4: "lower right"
- 5: "right"
- 6: "center left"
- 7: "center right"
- 8: "lower center"
- 9: "upper center"
- 10: "center"
decimals : :obj:`int`, optional
Number of decimal places on slice position annotation. If zero,
the slice position is integer without decimal point.
Default=0.
kwargs : :obj:`dict`
Extra keyword arguments are passed to matplotlib's text
function.
"""
kwargs = kwargs.copy()
if 'color' not in kwargs:
if self._black_bg:
kwargs['color'] = 'w'
else:
kwargs['color'] = 'k'
bg_color = ('k' if self._black_bg else 'w')
if left_right:
for display_axis in self.axes.values():
display_axis.draw_left_right(size=size, bg_color=bg_color,
**kwargs)
if positions:
for display_axis in self.axes.values():
display_axis.draw_position(size=size, bg_color=bg_color,
decimals=decimals,
**kwargs)
if scalebar:
axes = self.axes.values()
for display_axis in axes:
display_axis.draw_scale_bar(bg_color=bg_color,
fontsize=size,
size=scale_size,
units=scale_units,
loc=scale_loc,
**kwargs)
def close(self):
"""Close the figure.
This is necessary to avoid leaking memory.
"""
plt.close(self.frame_axes.figure.number)
def savefig(self, filename, dpi=None):
"""Save the figure to a file.
Parameters
----------
filename : :obj:`str`
The file name to save to. Its extension determines the
file type, typically '.png', '.svg' or '.pdf'.
dpi : ``None`` or scalar, optional
The resolution in dots per inch.
Default=None.
"""
facecolor = edgecolor = 'k' if self._black_bg else 'w'
self.frame_axes.figure.savefig(filename, dpi=dpi,
facecolor=facecolor,
edgecolor=edgecolor)
class OrthoSlicer(BaseSlicer):
"""A class to create 3 linked axes for plotting orthogonal
cuts of 3D maps. This visualization mode can be activated
from Nilearn plotting functions, like
:func:`~nilearn.plotting.plot_img`, by setting
``display_mode='ortho'``:
.. code-block:: python
from nilearn.datasets import load_mni152_template
from nilearn.plotting import plot_img
img = load_mni152_template()
# display is an instance of the OrthoSlicer class
display = plot_img(img, display_mode='ortho')
Attributes
----------
cut_coords : :obj:`list`
The cut coordinates.
axes : :obj:`dict` of :class:`~matplotlib.axes.Axes`
The 3 axes used to plot each view.
frame_axes : :class:`~matplotlib.axes.Axes`
The axes framing the whole set of views.
Notes
-----
The extent of the different axes are adjusted to fit the data
best in the viewing area.
See Also
--------
nilearn.plotting.displays.MosaicSlicer : Three cuts are performed \
along multiple rows and columns.
nilearn.plotting.displays.TiledSlicer : Three cuts are performed \
and arranged in a 2x2 grid.
"""
_cut_displayed = 'yxz'
_axes_class = CutAxes
@fill_doc
@classmethod
def find_cut_coords(cls, img=None, threshold=None, cut_coords=None):
"""Instantiate the slicer and find cut coordinates.
Parameters
----------
%(img)s
threshold : :obj:`int` or :obj:`float` or ``None``, optional
Threshold to apply:
- If ``None`` is given, the maps are not thresholded.
- If a number is given, it is used to threshold the maps,
values below the threshold (in absolute value) are plotted
as transparent.
Default=None.
cut_coords : 3 :obj:`tuple` of :obj:`int`
The cut position, in world space.
"""
if cut_coords is None:
if img is None or img is False:
cut_coords = (0, 0, 0)
else:
cut_coords = find_xyz_cut_coords(
img, activation_threshold=threshold)
cut_coords = [cut_coords['xyz'.find(c)]
for c in sorted(cls._cut_displayed)]
return cut_coords
def _init_axes(self, **kwargs):
cut_coords = self.cut_coords
if len(cut_coords) != len(self._cut_displayed):
raise ValueError('The number cut_coords passed does not'
' match the display_mode')
x0, y0, x1, y1 = self.rect
facecolor = 'k' if self._black_bg else 'w'
# Create our axes:
self.axes = dict()
for index, direction in enumerate(self._cut_displayed):
fh = self.frame_axes.get_figure()
ax = fh.add_axes([0.3 * index * (x1 - x0) + x0, y0,
.3 * (x1 - x0), y1 - y0], aspect='equal')
if _compare_version(matplotlib.__version__, '>=', "1.6"):
ax.set_facecolor(facecolor)
else:
ax.set_axis_bgcolor(facecolor)
ax.axis('off')
coord = self.cut_coords[
sorted(self._cut_displayed).index(direction)]
display_ax = self._axes_class(ax, direction, coord, **kwargs)
self.axes[direction] = display_ax
ax.set_axes_locator(self._locator)
if self._black_bg:
for ax in self.axes.values():
ax.ax.imshow(np.zeros((2, 2, 3)),
extent=[-5000, 5000, -5000, 5000],
zorder=-500, aspect='equal')
# To have a black background in PDF, we need to create a
# patch in black for the background
self.frame_axes.imshow(np.zeros((2, 2, 3)),
extent=[-5000, 5000, -5000, 5000],
zorder=-500, aspect='auto')
self.frame_axes.set_zorder(-1000)
def _locator(self, axes, renderer):
"""The locator function used by matplotlib to position axes.
Here we put the logic used to adjust the size of the axes.
"""
x0, y0, x1, y1 = self.rect
width_dict = dict()
# A dummy axes, for the situation in which we are not plotting
# all three (x, y, z) cuts
dummy_ax = self._axes_class(None, None, None)
width_dict[dummy_ax.ax] = 0
display_ax_dict = self.axes
if self._colorbar:
adjusted_width = self._colorbar_width / len(self.axes)
right_margin = self._colorbar_margin['right'] / len(self.axes)
ticks_margin = self._colorbar_margin['left'] / len(self.axes)
x1 = x1 - (adjusted_width + ticks_margin + right_margin)
for display_ax in display_ax_dict.values():
bounds = display_ax.get_object_bounds()
if not bounds:
# This happens if the call to _map_show was not
# successful. As it happens asynchronously (during a
# refresh of the figure) we capture the problem and
# ignore it: it only adds a non informative traceback
bounds = [0, 1, 0, 1]
xmin, xmax, ymin, ymax = bounds
width_dict[display_ax.ax] = (xmax - xmin)
total_width = float(sum(width_dict.values()))
for ax, width in width_dict.items():
width_dict[ax] = width / total_width * (x1 - x0)
direction_ax = []
for d in self._cut_displayed:
direction_ax.append(display_ax_dict.get(d, dummy_ax).ax)
left_dict = dict()
for idx, ax in enumerate(direction_ax):
left_dict[ax] = x0
for prev_ax in direction_ax[:idx]:
left_dict[ax] += width_dict[prev_ax]
return Bbox([[left_dict[axes], y0],
[left_dict[axes] + width_dict[axes], y1]])
def draw_cross(self, cut_coords=None, **kwargs):
"""Draw a crossbar on the plot to show where the cut is
performed.
Parameters
----------
cut_coords : 3-:obj:`tuple` of :obj:`float`, optional
The position of the cross to draw. If ``None`` is passed, the
``OrthoSlicer``'s cut coordinates are used.
kwargs : :obj:`dict`
Extra keyword arguments are passed to function
:func:`~matplotlib.pyplot.axhline`.
"""
if cut_coords is None:
cut_coords = self.cut_coords
coords = dict()
for direction in 'xyz':
coord = None
if direction in self._cut_displayed:
coord = cut_coords[
sorted(self._cut_displayed).index(direction)]
coords[direction] = coord
x, y, z = coords['x'], coords['y'], coords['z']
kwargs = kwargs.copy()
if 'color' not in kwargs:
if self._black_bg:
kwargs['color'] = '.8'
else:
kwargs['color'] = 'k'
if 'y' in self.axes:
ax = self.axes['y'].ax
if x is not None:
ax.axvline(x, ymin=.05, ymax=.95, **kwargs)
if z is not None:
ax.axhline(z, **kwargs)
if 'x' in self.axes:
ax = self.axes['x'].ax
if y is not None:
ax.axvline(y, ymin=.05, ymax=.95, **kwargs)
if z is not None:
ax.axhline(z, xmax=.95, **kwargs)
if 'z' in self.axes:
ax = self.axes['z'].ax
if x is not None:
ax.axvline(x, ymin=.05, ymax=.95, **kwargs)
if y is not None:
ax.axhline(y, **kwargs)
class TiledSlicer(BaseSlicer):
"""A class to create 3 axes for plotting orthogonal
cuts of 3D maps, organized in a 2x2 grid.
This visualization mode can be activated from Nilearn plotting functions,
like :func:`~nilearn.plotting.plot_img`, by setting
``display_mode='tiled'``:
.. code-block:: python
from nilearn.datasets import load_mni152_template
from nilearn.plotting import plot_img
img = load_mni152_template()
# display is an instance of the TiledSlicer class
display = plot_img(img, display_mode='tiled')
Attributes
----------
cut_coords : :obj:`list`
The cut coordinates.
axes : :obj:`dict` of :class:`~matplotlib.axes.Axes`
The 3 axes used to plot each view.
frame_axes : :class:`~matplotlib.axes.Axes`
The axes framing the whole set of views.
Notes
-----
The extent of the different axes are adjusted to fit the data
best in the viewing area.
See Also
--------
nilearn.plotting.displays.MosaicSlicer : Three cuts are performed \
along multiple rows and columns.
nilearn.plotting.displays.OrthoSlicer : Three cuts are performed \
and arranged in a 2x2 grid.
"""
_cut_displayed = 'yxz'
_axes_class = CutAxes
_default_figsize = [2.0, 6.0]
@classmethod
def find_cut_coords(cls, img=None, threshold=None, cut_coords=None):
"""Instantiate the slicer and find cut coordinates.
Parameters
----------
img : 3D :class:`~nibabel.nifti1.Nifti1Image`
The brain map.
threshold : :obj:`float`, optional
The lower threshold to the positive activation.
If ``None``, the activation threshold is computed using the
80% percentile of the absolute value of the map.
cut_coords : :obj:`list` of :obj:`float`, optional
xyz world coordinates of cuts.
Returns
-------
cut_coords : :obj:`list` of :obj:`float`
xyz world coordinates of cuts.
"""
if cut_coords is None:
if img is None or img is False:
cut_coords = (0, 0, 0)
else:
cut_coords = find_xyz_cut_coords(
img, activation_threshold=threshold)
cut_coords = [cut_coords['xyz'.find(c)]
for c in sorted(cls._cut_displayed)]
return cut_coords
def _find_initial_axes_coord(self, index):