コード例 #1
0
def plot_connectivity(con,
                      n_lines=None,
                      node_angles=None,
                      node_width=None,
                      node_colors=None,
                      facecolor='black',
                      textcolor='white',
                      node_edgecolor='black',
                      linewidth=1.5,
                      colormap='hot',
                      vmin=None,
                      vmax=None,
                      colorbar=True,
                      title=None,
                      colorbar_size=0.2,
                      colorbar_pos=(-0.3, 0.1),
                      fontsize_title=12,
                      fontsize_names=8,
                      fontsize_colorbar=8,
                      padding=6.,
                      fig=None,
                      subplot=111,
                      interactive=True,
                      node_linewidth=2.,
                      show=True):
    """Visualize parcellated connectivity as a circular graph.

    Parameters
    ----------
    con : instance of LabelConnectivity
        The parcellated connectivity to visualize.
    n_lines : int | None
        If not None, only the n_lines strongest connections
        (strength=abs(con)) are drawn.
    node_angles : array, shape=(len(node_names,)) | None
        Array with node positions in degrees. If None, the nodes are
        equally spaced on the circle. See :func:`mne.viz.circular_layout`.
    node_width : float | None
        Width of each node in degrees. If None, the minimum angle between
        any two nodes is used as the width.
    node_colors : list of tuples | list of str
        List with the color to use for each node. If fewer colors than
        nodes are provided, the colors will be repeated. Any color
        supported by matplotlib can be used, e.g., RGBA tuples, named
        colors.
    facecolor : str
        Color to use for background. See matplotlib.colors.
    textcolor : str
        Color to use for text. See matplotlib.colors.
    node_edgecolor : str
        Color to use for lines around nodes. See matplotlib.colors.
    linewidth : float
        Line width to use for connections.
    colormap : str
        Colormap to use for coloring the connections.
    vmin : float | None
        Minimum value for colormap. If None, it is determined
        automatically.
    vmax : float | None
        Maximum value for colormap. If None, it is determined
        automatically.
    colorbar : bool
        Display a colorbar or not.
    title : str
        The figure title.
    colorbar_size : float
        Size of the colorbar.
    colorbar_pos : 2-tuple
        Position of the colorbar.
    fontsize_title : int
        Font size to use for title.
    fontsize_names : int
        Font size to use for node names.
    fontsize_colorbar : int
        Font size to use for colorbar.
    padding : float
        Space to add around figure to accommodate long labels.
    fig : None | instance of matplotlib.pyplot.Figure
        The figure to use. If None, a new figure with the specified
        background color will be created.
    subplot : int | 3-tuple
        Location of the subplot when creating figures with multiple plots.
        E.g.  121 or (1, 2, 1) for 1 row, 2 columns, plot 1. See
        matplotlib.pyplot.subplot.
    interactive : bool
        When enabled, left-click on a node to show only connections to that
        node. Right-click shows all connections.
    node_linewidth : float
        Line with for nodes.
    show : bool
        Show figure if True.

    Returns
    -------
    fig : instance of matplotlib.pyplot.Figure
        The figure handle.
    axes : instance of matplotlib.axes.PolarAxesSubplot
        The subplot handle.
    """
    names = [l.name for l in con.labels]

    if node_colors is None:
        node_colors = [l.color for l in con.labels]

    if node_angles is None:
        # Try to construct a sensible default layout

        # First, we reorder the labels based on their location in the left
        # hemisphere.
        lh_labels = [name for name in names if name.endswith('lh')]

        # Get the y-location of the label
        label_ypos = list()
        for name in lh_labels:
            idx = names.index(name)
            ypos = np.mean(con.labels[idx].pos[:, 1])
            label_ypos.append(ypos)

        # Reorder the labels based on their location
        lh_labels = [
            label for (yp, label) in sorted(zip(label_ypos, lh_labels))
        ]

        # Second, we reorder the labels based on their location in the right
        # hemisphere.
        rh_labels = [name for name in names if name.endswith('rh')]
        # For the right hemi
        # Get the y-location of the label
        rlabel_ypos = list()
        for name in rh_labels:
            idx = names.index(name)
            ypos = np.mean(con.labels[idx].pos[:, 1])
            rlabel_ypos.append(ypos)

        # Reorder the labels based on their location
        rh_labels = [
            label
            for (yp,
                 label) in sorted(zip(rlabel_ypos, rh_labels), reverse=True)
        ]

        # Save the plot order and create a circular layout
        node_order = list()
        node_order.extend(lh_labels[::-1])  # reverse the order
        node_order.extend(rh_labels[::-1])  # reverse the order

        node_angles = circular_layout(names,
                                      node_order,
                                      start_pos=90,
                                      group_boundaries=[0, len(names) / 2])

    return plot_connectivity_circle(con.data,
                                    node_names=names,
                                    indices=con.pairs,
                                    n_lines=n_lines,
                                    node_angles=node_angles,
                                    node_width=node_width,
                                    node_colors=node_colors,
                                    facecolor=facecolor,
                                    textcolor=textcolor,
                                    node_edgecolor=node_edgecolor,
                                    linewidth=linewidth,
                                    colormap=colormap,
                                    vmin=vmin,
                                    vmax=vmax,
                                    colorbar=colorbar,
                                    title=title,
                                    colorbar_size=colorbar_size,
                                    colorbar_pos=colorbar_pos,
                                    fontsize_title=fontsize_title,
                                    fontsize_names=fontsize_names,
                                    fontsize_colorbar=fontsize_colorbar,
                                    padding=padding,
                                    fig=fig,
                                    interactive=interactive,
                                    node_linewidth=node_linewidth,
                                    show=show)
コード例 #2
0
ファイル: con_viz.py プロジェクト: nkampel/jumeg
def plot_grouped_connectivity_circle(yaml_fname, con, orig_labels,
                                     node_order_size=68,
                                     out_fname='circle.png', title=None,
                                     subplot=111, include_legend=False,
                                     n_lines=None, fig=None, show=True,
                                     vmin=None, vmax=None,
                                     colorbar=False):
    '''
    Plot the connectivity circle grouped and ordered according to
    groups in the yaml input file provided.
    orig_labels : list of str
        Label names in the order as appears in con.
    '''
    # read the yaml file with grouping
    if op.isfile(yaml_fname):
        with open(yaml_fname, 'r') as f:
            labels = yaml.load(f)
    else:
        print '%s - File not found.' % yaml_fname
        sys.exit()

    cortex_colors = ['m', 'b', 'y', 'c', 'r', 'g',
                     'g', 'r', 'c', 'y', 'b', 'm']

    # make list of label_names (without individual cortex locations)
    label_names = list()
    for lab in labels:
        label_names.extend(labels[lab])

    lh_labels = [name + '-lh' for name in label_names]
    rh_labels = [name + '-rh' for name in label_names]

    # Save the plot order and create a circular layout
    node_order = list()
    node_order.extend(lh_labels[::-1])  # reverse the order
    node_order.extend(rh_labels)

    assert len(node_order) == node_order_size, 'Node order length is correct.'

    # the respective no. of regions in each cortex
    group_bound = [len(labels[key]) for key in labels.keys()]
    group_bound = [0] + group_bound[::-1] + group_bound
    group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))]

    # remove the first element of group_bound
    # make label colours such that each cortex is of one colour
    group_bound.pop(0)
    label_colors = []
    for ind, rep in enumerate(group_bound):
        label_colors += [cortex_colors[ind]] * rep
    assert len(label_colors) == len(node_order), 'Number of colours do not match'

    # remove the last total sum of the list
    group_boundaries.pop()

    from mne.viz.circle import circular_layout
    node_angles = circular_layout(orig_labels, node_order, start_pos=90,
                                  group_boundaries=group_boundaries)

    # the order of the node_colors must match that of orig_labels
    # therefore below reordering is necessary
    reordered_colors = [label_colors[node_order.index(orig)]
                        for orig in orig_labels]

    # Plot the graph using node_order and colours
    # orig_labels is the order on nodes in the con matrix (important)
    from mne.viz import plot_connectivity_circle
    plot_connectivity_circle(con, orig_labels, n_lines=n_lines,
                             facecolor='white', textcolor='black',
                             node_angles=node_angles,
                             node_colors=reordered_colors,
                             node_edgecolor='white', fig=fig,
                             fontsize_names=6, vmax=vmax, vmin=vmin,
                             colorbar_size=0.2, colorbar_pos=(-0.3, 0.1),
                             colorbar=colorbar, show=show, subplot=subplot,
                             title=title)

    if include_legend:
        import matplotlib.patches as mpatches
        legend_patches = [mpatches.Patch(color=col, label=key)
                          for col, key in zip(['g', 'r', 'c', 'y', 'b', 'm'],
                                              labels.keys())]
        pl.legend(handles=legend_patches, loc=(0.02, 0.02), ncol=1,
                  mode=None, fontsize='small')
    if out_fname:
        pl.savefig(out_fname, facecolor='white', dpi=300)
コード例 #3
0
def plot_grouped_connectivity_circle(yaml_fname,
                                     con,
                                     orig_labels,
                                     labels_mode=None,
                                     node_order_size=68,
                                     indices=None,
                                     out_fname='circle.png',
                                     title=None,
                                     subplot=111,
                                     include_legend=False,
                                     n_lines=None,
                                     fig=None,
                                     show=True,
                                     vmin=None,
                                     vmax=None,
                                     colormap='hot',
                                     colorbar=False,
                                     colorbar_pos=(-0.3, 0.1),
                                     bbox_inches=None,
                                     tight_layout=None,
                                     **kwargs):
    '''
    Plot the connectivity circle grouped and ordered according to
    groups in the yaml input file provided.

    orig_labels : list of str
        Label names in the order as appears in con.

    labels_mode : str | None
        'blank' mode plots no labels on the circle plot,
        'cortex_only' plots only the name of the cortex on one representative
        node and None plots all of the orig_label names provided.

    bbox_inches : None | 'tight'

    tight_layout : bool

    NOTE: yaml order fix helps preserves the order of entries in the yaml file.
    '''
    import matplotlib.pyplot as plt
    # read the yaml file with grouping
    if op.isfile(yaml_fname):
        with open(yaml_fname, 'r') as f:
            labels = yaml.load(f)
    else:
        print '%s - File not found.' % yaml_fname
        sys.exit()

    cortex_colors = [
        'm', 'b', 'y', 'c', 'r', 'g', 'g', 'r', 'c', 'y', 'b', 'm'
    ]

    # make list of label_names (without individual cortex locations)
    label_names = list()
    for lab in labels:
        # label_names.extend(labels[lab])
        label_names += lab.values()[0]  # yaml order fix

    lh_labels = [name + '-lh' for name in label_names]
    rh_labels = [name + '-rh' for name in label_names]

    # Save the plot order and create a circular layout
    node_order = list()
    node_order.extend(lh_labels[::-1])  # reverse the order
    node_order.extend(rh_labels)

    assert len(node_order) == node_order_size, 'Node order length is correct.'

    # the respective no. of regions in each cortex
    # group_bound = [len(labels[key]) for key in labels.keys()]
    group_bound = [len(key.values()[0]) for key in labels]  # yaml order fix
    group_bound = [0] + group_bound[::-1] + group_bound
    group_boundaries = [
        sum(group_bound[:i + 1]) for i in range(len(group_bound))
    ]

    # remove the first element of group_bound
    # make label colours such that each cortex is of one colour
    group_bound.pop(0)
    label_colors = []
    for ind, rep in enumerate(group_bound):
        label_colors += [cortex_colors[ind]] * rep
    assert len(label_colors) == len(
        node_order), 'Number of colours do not match'

    # remove the last total sum of the list
    group_boundaries.pop()

    node_angles = circular_layout(orig_labels,
                                  node_order,
                                  start_pos=90,
                                  group_boundaries=group_boundaries)

    # the order of the node_colors must match that of orig_labels
    # therefore below reordering is necessary
    reordered_colors = [
        label_colors[node_order.index(orig)] for orig in orig_labels
    ]

    # labels mode decides the labels printed for each of the nodes
    if labels_mode is 'blank':
        # show nothing, only the empty circle plot
        my_labels = ['' for orig in orig_labels]
    elif labels_mode is 'cortex_only':
        # show only the names of cortex areas on one representative node
        replacer = dict({
            'caudalanteriorcingulate': 'cingulate',
            'insula': 'insula',
            'parstriangularis': 'frontal',
            'precuneus': 'parietal',
            'lingual': 'occipital',
            'transversetemporal': 'temporal'
        })

        replaced_labels = []
        for myl in orig_labels:
            if myl.split('-lh')[0] in replacer.keys():
                replaced_labels.append(replacer[myl.split('-lh')[0]] + '-lh')
            elif myl.split('-rh')[0] in replacer.keys():
                replaced_labels.append(replacer[myl.split('-rh')[0]] + '-rh')
            else:
                replaced_labels.append('')
        my_labels = replaced_labels
    else:
        # show all the node labels as originally given
        my_labels = orig_labels

    # Plot the graph using node_order and colours
    # orig_labels is the order of nodes in the con matrix (important)
    fig, axes = plot_connectivity_circle(con,
                                         my_labels,
                                         n_lines=n_lines,
                                         facecolor='white',
                                         textcolor='black',
                                         node_angles=node_angles,
                                         colormap=colormap,
                                         node_colors=reordered_colors,
                                         node_edgecolor='white',
                                         fig=fig,
                                         fontsize_title=12,
                                         fontsize_names=10,
                                         padding=2.,
                                         vmax=vmax,
                                         vmin=vmin,
                                         colorbar_size=0.2,
                                         colorbar_pos=colorbar_pos,
                                         colorbar=colorbar,
                                         show=show,
                                         subplot=subplot,
                                         indices=indices,
                                         title=title,
                                         **kwargs)

    if include_legend:
        import matplotlib.patches as mpatches
        # yaml order fix
        legend_patches = [
            mpatches.Patch(color=col, label=llab.keys()[0])
            for col, llab in zip(['g', 'r', 'c', 'y', 'b', 'm'], labels)
        ]
        # legend_patches = [mpatches.Patch(color=col, label=key)
        #                   for col, key in zip(['g', 'r', 'c', 'y', 'b', 'm'],
        #                                       labels.keys())]
        plt.legend(handles=legend_patches,
                   loc=3,
                   ncol=1,
                   mode=None,
                   fontsize='medium')

    if tight_layout:
        fig.tight_layout()

    if out_fname:
        fig.savefig(out_fname,
                    facecolor='white',
                    dpi=600,
                    bbox_inches=bbox_inches)

    return fig