# Buggy code
def _label_clicked(pos, params):
    """Function for plotting independent components on click to label."""
    import matplotlib.pyplot as plt

    offsets = np.array(params["offsets"]) + params["offsets"][0]
    line_idx = np.searchsorted(offsets, pos[1]) + params["ch_start"]
    if line_idx >= len(params["picks"]):
        return
    ic_idx = [params["picks"][line_idx]]
    types = list()
    info = params["ica"].info
    if len(pick_types(info, meg=False, eeg=True, ref_meg=False)) > 0:
        types.append("eeg")
    if len(pick_types(info, meg="mag", ref_meg=False)) > 0:
        types.append("mag")
    if len(pick_types(info, meg="grad", ref_meg=False)) > 0:
        types.append("grad")

    ica = params["ica"]
    data = np.dot(
        ica.mixing_matrix_[:, ic_idx].T, ica.pca_components_[: ica.n_components_]
    )
    data = np.atleast_2d(data)
    fig, axes = _prepare_trellis(len(types), max_col=3)
    for ch_idx, ch_type in enumerate(types):
        try:
            data_picks, pos, merge_grads, _, _ = _prepare_topo_plot(ica, ch_type, None)
        except Exception as exc:
            warn(exc)
            plt.close(fig)
            return
        this_data = data[:, data_picks]
        ax = axes[ch_idx]
        if merge_grads:
            from ..channels.layout import _merge_grad_data
        for ii, data_ in zip(ic_idx, this_data):
            ax.set_title("IC #%03d " % ii + ch_type, fontsize=12)
            data_ = _merge_grad_data(data_) if merge_grads else data_
            plot_topomap(data_.flatten(), pos, axis=ax, show=False)
            ax.set_yticks([])
            ax.set_xticks([])
            ax.set_frame_on(False)
    tight_layout(fig=fig)
    fig.subplots_adjust(top=0.95)
    fig.canvas.draw()
    plt_show(True)


# Traceback (AttributeError)
In [51]: ica.plot_components()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-51-31baf63ee5ff> in <module>()
----> 1 ica.plot_components()

/Applications/packages/mne-python/mne/preprocessing/ica.py in plot_components(self, picks, ch_type, res, layout, vmin, vmax, cmap, sensors, colorbar, title, show, outlines, contours, image_interp, head_pos)
1384                                    outlines=outlines, contours=contours,
1385                                    image_interp=image_interp,
-> 1386                                    head_pos=head_pos)
1387
1388     def plot_sources(self, inst, picks=None, exclude=None, start=None,

/Applications/packages/mne-python/mne/viz/topomap.py in plot_ica_components(ica, picks, ch_type, res, layout, vmin, vmax, cmap, sensors, colorbar, title, show, outlines, contours, image_interp, head_pos)
748                                       show=show, outlines=outlines,
749                                       contours=contours,
--> 750                                       image_interp=image_interp)
751             figs.append(fig)
752         return figs

/Applications/packages/mne-python/mne/viz/topomap.py in plot_ica_components(ica, picks, ch_type, res, layout, vmin, vmax, cmap, sensors, colorbar, title, show, outlines, contours, image_interp, head_pos)
799     tight_layout(fig=fig)
800     fig.subplots_adjust(top=0.95)
--> 801     fig.canvas.draw()
802     plt_show(show)
803     return fig

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.pyc in draw(self)
146         # causes problems with code that uses the result of the
147         # draw() to update plot elements.
--> 148         FigureCanvasAgg.draw(self)
149         self._priv_update()
150

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
467
468         try:
--> 469             self.figure.draw(self.renderer)
470         finally:
471             RendererAgg.lock.release()

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
57     def draw_wrapper(artist, renderer, *args, **kwargs):
58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
60         after(artist, renderer)
61

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
1015         if self.get_tight_layout() and self.axes:
1016             try:
-> 1017                 self.tight_layout(renderer, **self._tight_parameters)
1018             except ValueError:
1019                 pass

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/figure.pyc in tight_layout(self, renderer, pad, h_pad, w_pad, rect)
1661                                          renderer,
1662                                          pad=pad, h_pad=h_pad, w_pad=w_pad,
-> 1663                                          rect=rect)
1664
1665         self.subplots_adjust(**kwargs)

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/tight_layout.pyc in get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, pad, h_pad, w_pad, rect)
350                                      subplot_list=subplot_list,
351                                      ax_bbox_list=ax_bbox_list,
--> 352                                      pad=pad, h_pad=h_pad, w_pad=w_pad)
353
354     if rect is not None:

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/tight_layout.pyc in auto_adjust_subplotpars(fig, renderer, nrows_ncols, num1num2_list, subplot_list, ax_bbox_list, pad, h_pad, w_pad, rect)
129         tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots])
130         tight_bbox = TransformedBbox(tight_bbox_raw,
--> 131                                      fig.transFigure.inverted())
132
133         row1, col1 = divmod(num1, cols)

/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/transforms.pyc in __init__(self, bbox, transform, **kwargs)
1055         *transform*: a 2D :class:`Transform`
1056         """
-> 1057         assert bbox.is_bbox
1058         assert isinstance(transform, Transform)
1059         assert transform.input_dims == 2

In [52]: ica.plot_components()
AttributeError: 'NoneType' object has no attribute 'is_bbox'

In [52]: Traceback (most recent call last):
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 427, in idle_draw
self.draw()
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 148, in draw
FigureCanvasAgg.draw(self)
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 469, in draw
self.figure.draw(self.renderer)
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/figure.py", line 1017, in draw
self.tight_layout(renderer, **self._tight_parameters)
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/figure.py", line 1663, in tight_layout
rect=rect)
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/tight_layout.py", line 352, in get_tight_layout_figure
pad=pad, h_pad=h_pad, w_pad=w_pad)
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/tight_layout.py", line 131, in auto_adjust_subplotpars
fig.transFigure.inverted())
File "/Users/teon/anaconda/lib/python2.7/site-packages/matplotlib/transforms.py", line 1057, in __init__
assert bbox.is_bbox
AttributeError: 'NoneType' object has no attribute 'is_bbox'

If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev@scipy.org

You can print a more detailed traceback right now with "%tb", or use "%debug"
to interactively debug it.

Extra-detailed tracebacks for bug-reporting purposes can be enabled via:
%config Application.verbose_crash=True

# Fixed code
def _label_clicked(pos, params):
    """Function for plotting independent components on click to label."""
    import matplotlib.pyplot as plt

    offsets = np.array(params["offsets"]) + params["offsets"][0]
    line_idx = np.searchsorted(offsets, pos[1]) + params["ch_start"]
    if line_idx >= len(params["picks"]):
        return
    ic_idx = [params["picks"][line_idx]]
    types = list()
    info = params["ica"].info
    if len(pick_types(info, meg=False, eeg=True, ref_meg=False)) > 0:
        types.append("eeg")
    if len(pick_types(info, meg="mag", ref_meg=False)) > 0:
        types.append("mag")
    if len(pick_types(info, meg="grad", ref_meg=False)) > 0:
        types.append("grad")

    ica = params["ica"]
    data = np.dot(
        ica.mixing_matrix_[:, ic_idx].T, ica.pca_components_[: ica.n_components_]
    )
    data = np.atleast_2d(data)
    fig, axes = _prepare_trellis(len(types), max_col=3)
    for ch_idx, ch_type in enumerate(types):
        try:
            data_picks, pos, merge_grads, _, _ = _prepare_topo_plot(ica, ch_type, None)
        except Exception as exc:
            warn(exc)
            plt.close(fig)
            return
        this_data = data[:, data_picks]
        ax = axes[ch_idx]
        if merge_grads:
            from ..channels.layout import _merge_grad_data
        for ii, data_ in zip(ic_idx, this_data):
            ax.set_title("IC #%03d " % ii + ch_type, fontsize=12)
            data_ = _merge_grad_data(data_) if merge_grads else data_
            plot_topomap(data_.flatten(), pos, axis=ax, show=False)
            _hide_frame(ax)
    tight_layout(fig=fig)
    fig.subplots_adjust(top=0.95)
    fig.canvas.draw()
    plt_show(True)