コード例 #1
0
ファイル: viz.py プロジェクト: SerialDev/sdev_py_utils
def nx_plot(graph, name=""):
    print(graph.name, len(graph.edges))
    nodes, edges = nx_layout(graph)

    direct = connect_edges(nodes, edges)
    bundled_bw005 = hammer_bundle(nodes, edges)
    bundled_bw030 = hammer_bundle(nodes, edges, initial_bandwidth=0.30)

    return [
        graphplot(nodes, direct, graph.name),
        graphplot(nodes, bundled_bw005, "Bundled bw=0.05"),
        graphplot(nodes, bundled_bw030, "Bundled bw=0.30")
    ]
コード例 #2
0
def ds_plot(G,
            layout='circular',
            method='direct',
            bw=0.05,
            name='',
            kwargs=cvsopts):
    '''
    Returns graph plot using datashader layout
    fir nodes positions from circular (default),
    forceatlas2 or random position layout.

    Accepted vars:
        G => network graph obj
        layout => circular; forceatlas2; random
        method => connect; bundle
        bw => initial bandwith for bundled
        name => title or label
    '''
    n, e = nx_layout(G)
    nodes = ds_layout(n, e, layout)
    if method == 'bundle':
        edges = hammer_bundle(nodes, e, initial_bandwidth=bw)
    else:  # lightweight
        edges = connect_edges(nodes, e)
    return graph_plot(nodes, edges, name, kwargs=kwargs)
コード例 #3
0
def test_hammer_bundle_with_weights(nodes, weighted_edges, include_edge_id):
    # Expect four lines starting at center (0.0, 0.0) and terminating
    # with NaN
    data = pd.DataFrame({'edge_id':
                            [1.0, np.nan, 2.0, np.nan,
                             3.0, np.nan, 4.0, np.nan],
                         'x':
                            [0.0, np.nan, 0.0, np.nan,
                             0.0, np.nan, 0.0, np.nan],
                         'y':
                            [0.0, np.nan, 0.0, np.nan,
                             0.0, np.nan, 0.0, np.nan],
                         'weight':
                            [1.0, np.nan, 1.0, np.nan,
                             1.0, np.nan, 1.0, np.nan]})
    columns = ['edge_id', 'x', 'y', 'weight'] if include_edge_id else ['x', 'y', 'weight']
    expected = pd.DataFrame(data, columns=columns)

    df = hammer_bundle(nodes, weighted_edges, include_edge_id=include_edge_id)

    starts = df[(df.x == 0.0) & (df.y == 0.0)]
    ends = df[df.isnull().any(axis=1)]
    given = pd.concat([starts, ends])
    given.sort_index(inplace=True)
    given.reset_index(drop=True, inplace=True)

    assert given.equals(expected)
コード例 #4
0
ファイル: test_bundling.py プロジェクト: jsignell/datashader
def test_hammer_bundle_with_weights(nodes, weighted_edges, include_edge_id):
    # Expect four lines starting at center (0.0, 0.0) and terminating
    # with NaN
    data = pd.DataFrame({'edge_id':
                            [1.0, np.nan, 2.0, np.nan,
                             3.0, np.nan, 4.0, np.nan],
                         'x':
                            [0.0, np.nan, 0.0, np.nan,
                             0.0, np.nan, 0.0, np.nan],
                         'y':
                            [0.0, np.nan, 0.0, np.nan,
                             0.0, np.nan, 0.0, np.nan],
                         'weight':
                            [1.0, np.nan, 1.0, np.nan,
                             1.0, np.nan, 1.0, np.nan]})
    columns = ['edge_id', 'x', 'y', 'weight'] if include_edge_id else ['x', 'y', 'weight']
    expected = pd.DataFrame(data, columns=columns)

    df = hammer_bundle(nodes, weighted_edges, include_edge_id=include_edge_id)

    starts = df[(df.x == 0.0) & (df.y == 0.0)]
    ends = df[df.isnull().any(axis=1)]
    given = pd.concat([starts, ends])
    given.sort_index(inplace=True)
    given.reset_index(drop=True, inplace=True)

    assert given.equals(expected)
コード例 #5
0
def test_hammer_bundle(nodes, edges):
    # Expect four lines starting at center (0.5, 0.5) and terminating
    # with NaN
    data = pd.DataFrame({'x': [0.5, np.nan, 0.5, np.nan,
                               0.5, np.nan, 0.5, np.nan],
                         'y': [0.5, np.nan, 0.5, np.nan,
                               0.5, np.nan, 0.5, np.nan]})
    expected = pd.DataFrame(data)

    df = hammer_bundle(nodes, edges)

    starts = df[(df.x == 0.5) & (df.y == 0.5)]
    ends = df[df.isnull().any(axis=1)]
    given = pd.concat([starts, ends])
    given.sort_index(inplace=True)
    given.reset_index(drop=True, inplace=True)

    assert_eq(given, expected)
コード例 #6
0
ファイル: test_bundling.py プロジェクト: whoget/datashader
def test_hammer_bundle_without_weights(nodes, edges):
    # Expect four lines starting at center (0.0, 0.0) and terminating
    # with NaN
    data = pd.DataFrame({
        'x': [0.0, np.nan, 0.0, np.nan, 0.0, np.nan, 0.0, np.nan],
        'y': [0.0, np.nan, 0.0, np.nan, 0.0, np.nan, 0.0, np.nan]
    })
    expected = pd.DataFrame(data, columns=['x', 'y'])

    df = hammer_bundle(nodes, edges)

    starts = df[(df.x == 0.0) & (df.y == 0.0)]
    ends = df[df.isnull().any(axis=1)]
    given = pd.concat([starts, ends])
    given.sort_index(inplace=True)
    given.reset_index(drop=True, inplace=True)

    assert given.equals(expected)
コード例 #7
0
 def make_bundles(nodes, edges):
     node_name_map = {
         x: n + 1
         for n, x in enumerate(list(nodes)) if x in self.positions
     }
     n = pd.DataFrame(
         [[node_name_map[k]] + list(map(float, v))
          for k, v in self.positions.items() if k in node_name_map],
         columns=['id', 'x', 'y'])
     e = pd.DataFrame(
         [[node_name_map[y] for y in x[:2]]
          for x in edges if x[2]['weight'] > self.edgeMinWeight
          and x[0] in node_name_map and x[1] in node_name_map],
         columns=['source', 'target'])
     bundles = hammer_bundle(n,
                             e,
                             decay=self.bundleDecay,
                             initial_bandwidth=self.bundleBw)
     return bundles[~bundles.isna().any(axis=1)].values
コード例 #8
0
def on_server_loaded(server_context):
    # Load the raw NX GRAPH, compute ForceLayout node position, and Hammer_bundle the edges
    r_graph_file = os.getenv('CF_GRAPH')
    logger.info('Loading CF_GRAPH={}'.format(r_graph_file))

    r_graph = nx.read_yaml(r_graph_file)
    pd_nodes = pd.DataFrame([(node, node) for node in r_graph.nodes],
                            columns=['id', 'node'])
    pd_nodes.set_index('id', inplace=True)
    pd_edges = pd.DataFrame(list(r_graph.edges), columns=['source', 'target'])

    logger.info('Laying out {} nodes'.format(len(pd_nodes)))
    pd_nodes_layout = forceatlas2_layout(pd_nodes, pd_edges)
    pd_nodes_layout.to_pickle('nodes.pkl')

    logger.info('Bundling {} edges'.format(len(pd_edges)))
    h_bundle = hammer_bundle(pd_nodes_layout, pd_edges)
    h_bundle.to_pickle('edges-bundled.pkl')

    return
コード例 #9
0
ファイル: simulations.py プロジェクト: safreita1/TIGER
    def get_graph_coordinates(self):
        """
        Gets the graph coordinates, which can be:
        (1) set in the graph itself with the 'pos' tag on the vertices,
        (2) positioned according to the force atlas2 algorithm,
        (3) positioned using a spectral layout.

        Then lays out the edges, can be curved, bundled, or straight

        :return: Tuple containing node and edge positions
        """
        edge_pos = None

        node_pos = {
            idx: v['pos']
            for idx, (k, v) in enumerate(dict(self.graph.nodes).items())
            if 'pos' in v
        }  # check graph for coords
        node_pos = node_pos if len(node_pos) == len(self.graph) else None

        # node positions
        if self.prm['node_style'] == 'force_atlas' and node_pos is None:
            force = ForceAtlas2(outboundAttractionDistribution=True,
                                edgeWeightInfluence=0,
                                scalingRatio=6.0,
                                verbose=False)
            node_pos = force.forceatlas2_networkx_layout(
                self.graph, pos=None, iterations=self.prm['fa_iter'])

        elif node_pos is None:
            node_pos = nx.spectral_layout(self.graph)

        # edge positions
        if self.prm['edge_style'] == 'bundled':
            pos = pd.DataFrame.from_dict(
                node_pos, orient='index',
                columns=['x', 'y']).rename_axis('name').reset_index()
            edge_pos = hammer_bundle(pos, nx.to_pandas_edgelist(self.graph))

        return node_pos, edge_pos
コード例 #10
0
 def plot_graph(self, method='networkx', options={}):
     digr = self.make_graph()
     if method == 'networkx':
         dflt_options = {
             'node_color': 'black',
             'node_size': 20,
             'width': 1,
         }
         opts = {**dflt_options, **options}
         nx.draw_kamada_kawai(digr, **opts)
     elif method == 'datashader':
         digr = digr.to_undirected()
         nodes = pd.DataFrame(digr.nodes(), columns=['name'])
         edges = pd.DataFrame(digr.edges(), columns=['source', 'target'])
         iterations = {
             'iterations': int(np.ceil(np.sqrt(len(nodes)))),
             **options
         }['iterations']
         fd = forceatlas2_layout(nodes, edges, iterations=iterations)
         bundle = {'bundle': False, **options}['bundle']
         if bundle:
             return graphplot(fd, hammer_bundle(fd, edges))
         else:
             return graphplot(fd, connect_edges(fd, edges))
コード例 #11
0
def connectivity_base(
    x: int,
    y: int,
    edge_df: pd.DataFrame,
    highlights: Optional[list] = None,
    edge_bundling: Optional[str] = None,
    edge_cmap: str = "gray_r",
    show_points: bool = True,
    labels: Optional[list] = None,
    values: Optional[list] = None,
    theme: Optional[str] = None,
    cmap: str = "Blues",
    color_key: Union[dict, list, None] = None,
    color_key_cmap: str = "Spectral",
    background: str = "black",
    figsize: tuple = (7, 5),
    ax: Optional[Axes] = None,
    sort: str = "raw",
    save_show_or_return: str = "return",
    save_kwargs: dict = {},
) -> Union[None, Axes]:
    """Plot connectivity relationships of the underlying UMAP
    simplicial set data structure. Internally UMAP will make
    use of what can be viewed as a weighted graph. This graph
    can be plotted using the layout provided by UMAP as a
    potential diagnostic view of the embedding. Currently this only works
    for 2D embeddings. While there are many optional parameters
    to further control and tailor the plotting, you need only
    pass in the trained/fit umap model to get results. This plot
    utility will attempt to do the hard work of avoiding
    overplotting issues and provide options for plotting the
    points as well as using edge bundling for graph visualization.

    Parameters
    ----------
        x: `int`
            The first component of the embedding.
        y: `int`
            The second component of the embedding.
        edge_df `pd.DataFrame`
            The dataframe denotes the graph edge pairs. The three columns
            include 'source', 'target' and 'weight'.
        highlights: `list`, `list of list` or None (default: `None`)
            The list that cells will be restricted to.
        edge_bundling: string or None (optional, default None)
            The edge bundling method to use. Currently supported
            are None or 'hammer'. See the datashader docs
            on graph visualization for more details.
        edge_cmap: string (default 'gray_r')
            The name of a matplotlib colormap to use for shading/
            coloring the edges of the connectivity graph. Note that
            the ``theme``, if specified, will override this.
        show_points: bool (optional False)
            Whether to display the points over top of the edge
            connectivity. Further options allow for coloring/
            shading the points accordingly.
        labels: array, shape (n_samples,) (optional, default None)
            An array of labels (assumed integer or categorical),
            one for each data sample.
            This will be used for coloring the points in
            the plot according to their label. Note that
            this option is mutually exclusive to the ``values``
            option.
        values: array, shape (n_samples,) (optional, default None)
            An array of values (assumed float or continuous),
            one for each sample.
            This will be used for coloring the points in
            the plot according to a colorscale associated
            to the total range of values. Note that this
            option is mutually exclusive to the ``labels``
            option.
        theme: string (optional, default None)
            A color theme to use for plotting. A small set of
            predefined themes are provided which have relatively
            good aesthetics. Available themes are:
               * 'blue'
               * 'red'
               * 'green'
               * 'inferno'
               * 'fire'
               * 'viridis'
               * 'darkblue'
               * 'darkred'
               * 'darkgreen'
        cmap: string (optional, default 'Blues')
            The name of a matplotlib colormap to use for coloring
            or shading points. If no labels or values are passed
            this will be used for shading points according to
            density (largely only of relevance for very large
            datasets). If values are passed this will be used for
            shading according the value. Note that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        color_key: dict or array, shape (n_categories) (optional, default None)
            A way to assign colors to categoricals. This can either be
            an explicit dict mapping labels to colors (as strings of form
            '#RRGGBB'), or an array like object providing one color for
            each distinct category being provided in ``labels``. Either
            way this mapping will be used to color points according to
            the label. Note that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        color_key_cmap: string (optional, default 'Spectral')
            The name of a matplotlib colormap to use for categorical coloring.
            If an explicit ``color_key`` is not given a color mapping for
            categories can be generated from the label list and selecting
            a matching list of colors from the given colormap. Note
            that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        background: string (optional, default 'white)
            The color of the background. Usually this will be either
            'white' or 'black', but any color name will work. Ideally
            one wants to match this appropriately to the colors being
            used for points etc. This is one of the things that themes
            handle for you. Note that if theme
            is passed then this value will be overridden by the
            corresponding option of the theme.
        width: int (optional, default 800)
            The desired width of the plot in pixels.
        height: int (optional, default 800)
            The desired height of the plot in pixels
        sort: `str` (optional, default `raw`)
            The method to reorder data so that high values points will be on top of background points. Can be one of
            {'raw', 'abs'}, i.e. sorted by raw data or sort by absolute values.
        save_show_or_return: {'show', 'save', 'return'} (default: `return`)
            Whether to save, show or return the figure.
        save_kwargs: `dict` (default: `{}`)
            A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
            will use the {"path": None, "prefix": 'connectivity_base', "dpi": None, "ext": 'pdf', "transparent": True, "close":
            True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
            according to your needs.

    Returns
    -------
    result:
        Either return None or a matplotlib axis with the relevant plot displayed based on arguments.
        If you are using a notbooks and have ``%matplotlib inline`` set
        then this will simply display inline.
    """

    import matplotlib.pyplot as plt
    import datashader as ds
    import datashader.transfer_functions as tf
    import datashader.bundling as bd

    dpi = plt.rcParams["figure.dpi"]

    if theme is not None:
        cmap = _themes[theme]["cmap"]
        color_key_cmap = _themes[theme]["color_key_cmap"]
        edge_cmap = _themes[theme]["edge_cmap"]
        background = _themes[theme]["background"]

    points = np.array([x, y]).T
    point_df = pd.DataFrame(points, columns=("x", "y"))

    point_size = 500.0 / np.sqrt(points.shape[0])
    if point_size > 1:
        px_size = int(np.round(point_size))
    else:
        px_size = 1

    if show_points:
        edge_how = "log"
    else:
        edge_how = "eq_hist"

    extent = _get_extent(points)
    canvas = ds.Canvas(
        plot_width=int(figsize[0] * dpi),
        plot_height=int(figsize[1] * dpi),
        x_range=(extent[0], extent[1]),
        y_range=(extent[2], extent[3]),
    )

    if edge_bundling is None:
        edges = bd.directly_connect_edges(point_df, edge_df, weight="weight")
    elif edge_bundling == "hammer":
        warn("Hammer edge bundling is expensive for large graphs!\n"
             "This may take a long time to compute!")
        edges = bd.hammer_bundle(point_df, edge_df, weight="weight")
    else:
        raise ValueError(
            "{} is not a recognised bundling method".format(edge_bundling))

    edge_img = tf.shade(
        canvas.line(edges, "x", "y", agg=ds.sum("weight")),
        cmap=plt.get_cmap(edge_cmap),
        how=edge_how,
    )
    edge_img = tf.set_background(edge_img, background)

    if show_points:
        point_img = _datashade_points(
            points,
            None,
            labels,
            values,
            highlights,
            cmap,
            color_key,
            color_key_cmap,
            None,
            figsize[0] * dpi,
            figsize[1] * dpi,
            True,
            sort=sort,
        )
        if px_size > 1:
            point_img = tf.dynspread(point_img, threshold=0.5, max_px=px_size)
        result = tf.stack(edge_img, point_img, how="over")
    else:
        result = edge_img

    if ax is None:
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111)

    _embed_datashader_in_an_axis(result, ax)

    ax.set(xticks=[], yticks=[])

    if save_show_or_return == "save":
        s_kwargs = {
            "path": None,
            "prefix": "connectivity_base",
            "dpi": None,
            "ext": "pdf",
            "transparent": True,
            "close": True,
            "verbose": True,
        }
        s_kwargs = update_dict(s_kwargs, save_kwargs)

        save_fig(**s_kwargs)
    elif save_show_or_return == "show":
        plt.tight_layout()
        plt.show()
    elif save_show_or_return == "return":
        return ax
コード例 #12
0
ファイル: plot.py プロジェクト: sunny1205124/umap-1
def connectivity(
    umap_object,
    edge_bundling=None,
    edge_cmap="gray_r",
    show_points=False,
    labels=None,
    values=None,
    theme=None,
    cmap="Blues",
    color_key=None,
    color_key_cmap="Spectral",
    background="white",
    width=800,
    height=800,
):
    """Plot connectivity relationships of the underlying UMAP
    simplicial set data structure. Internally UMAP will make
    use of what can be viewed as a weighted graph. This graph
    can be plotted using the layout provided by UMAP as a
    potential diagnostic view of the embedding. Currently this only works
    for 2D embeddings. While there are many optional parameters
    to further control and tailor the plotting, you need only
    pass in the trained/fit umap model to get results. This plot
    utility will attempt to do the hard work of avoiding
    overplotting issues and provide options for plotting the
    points as well as using edge bundling for graph visualization.

    Parameters
    ----------
    umap_object: trained UMAP object
        A trained UMAP object that has a 2D embedding.

    edge_bundling: string or None (optional, default None)
        The edge bundling method to use. Currently supported
        are None or 'hammer'. See the datashader docs
        on graph visualization for more details.

    edge_cmap: string (default 'gray_r')
        The name of a matplotlib colormap to use for shading/
        coloring the edges of the connectivity graph. Note that
        the ``theme``, if specified, will override this.

    show_points: bool (optional False)
        Whether to display the points over top of the edge
        connectivity. Further options allow for coloring/
        shading the points accordingly.

    labels: array, shape (n_samples,) (optional, default None)
        An array of labels (assumed integer or categorical),
        one for each data sample.
        This will be used for coloring the points in
        the plot according to their label. Note that
        this option is mutually exclusive to the ``values``
        option.

    values: array, shape (n_samples,) (optional, default None)
        An array of values (assumed float or continuous),
        one for each sample.
        This will be used for coloring the points in
        the plot according to a colorscale associated
        to the total range of values. Note that this
        option is mutually exclusive to the ``labels``
        option.

    theme: string (optional, default None)
        A color theme to use for plotting. A small set of
        predefined themes are provided which have relatively
        good aesthetics. Available themes are:
           * 'blue'
           * 'red'
           * 'green'
           * 'inferno'
           * 'fire'
           * 'viridis'
           * 'darkblue'
           * 'darkred'
           * 'darkgreen'

    cmap: string (optional, default 'Blues')
        The name of a matplotlib colormap to use for coloring
        or shading points. If no labels or values are passed
        this will be used for shading points according to
        density (largely only of relevance for very large
        datasets). If values are passed this will be used for
        shading according the value. Note that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    color_key: dict or array, shape (n_categories) (optional, default None)
        A way to assign colors to categoricals. This can either be
        an explicit dict mapping labels to colors (as strings of form
        '#RRGGBB'), or an array like object providing one color for
        each distinct category being provided in ``labels``. Either
        way this mapping will be used to color points according to
        the label. Note that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    color_key_cmap: string (optional, default 'Spectral')
        The name of a matplotlib colormap to use for categorical coloring.
        If an explicit ``color_key`` is not given a color mapping for
        categories can be generated from the label list and selecting
        a matching list of colors from the given colormap. Note
        that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    background: string (optional, default 'white)
        The color of the background. Usually this will be either
        'white' or 'black', but any color name will work. Ideally
        one wants to match this appropriately to the colors being
        used for points etc. This is one of the things that themes
        handle for you. Note that if theme
        is passed then this value will be overridden by the
        corresponding option of the theme.

    width: int (optional, default 800)
        The desired width of the plot in pixels.

    height: int (optional, default 800)
        The desired height of the plot in pixels

    Returns
    -------
    result: matplotlib axis
        The result is a matplotlib axis with the relevant plot displayed.
        If you are using a notbooks and have ``%matplotlib inline`` set
        then this will simply display inline.
    """
    if theme is not None:
        cmap = _themes[theme]["cmap"]
        color_key_cmap = _themes[theme]["color_key_cmap"]
        edge_cmap = _themes[theme]["edge_cmap"]
        background = _themes[theme]["background"]

    points = umap_object.embedding_
    point_df = pd.DataFrame(points, columns=("x", "y"))

    point_size = 100.0 / np.sqrt(points.shape[0])
    if point_size > 1:
        px_size = int(np.round(point_size))
    else:
        px_size = 1

    if show_points:
        edge_how = "log"
    else:
        edge_how = "eq_hist"

    coo_graph = umap_object.graph_.tocoo()
    edge_df = pd.DataFrame(
        np.vstack([coo_graph.row, coo_graph.col, coo_graph.data]).T,
        columns=("source", "target", "weight"),
    )
    edge_df["source"] = edge_df.source.astype(np.int32)
    edge_df["target"] = edge_df.target.astype(np.int32)

    extent = _get_extent(points)
    canvas = ds.Canvas(
        plot_width=width,
        plot_height=height,
        x_range=(extent[0], extent[1]),
        y_range=(extent[2], extent[3]),
    )

    if edge_bundling is None:
        edges = bd.directly_connect_edges(point_df, edge_df, weight="weight")
    elif edge_bundling == "hammer":
        warn("Hammer edge bundling is expensive for large graphs!\n"
             "This may take a long time to compute!")
        edges = bd.hammer_bundle(point_df, edge_df, weight="weight")
    else:
        raise ValueError(
            "{} is not a recognised bundling method".format(edge_bundling))

    edge_img = tf.shade(
        canvas.line(edges, "x", "y", agg=ds.sum("weight")),
        cmap=plt.get_cmap(edge_cmap),
        how=edge_how,
    )
    edge_img = tf.set_background(edge_img, background)

    if show_points:
        point_img = _datashade_points(
            points,
            None,
            labels,
            values,
            cmap,
            color_key,
            color_key_cmap,
            None,
            width,
            height,
            False,
        )
        if px_size > 1:
            point_img = tf.dynspread(point_img, threshold=0.5, max_px=px_size)
        result = tf.stack(edge_img, point_img, how="over")
    else:
        result = edge_img

    font_color = _select_font_color(background)

    dpi = plt.rcParams["figure.dpi"]
    fig = plt.figure(figsize=(width / dpi, height / dpi))
    ax = fig.add_subplot(111)

    _embed_datashader_in_an_axis(result, ax)

    ax.set(xticks=[], yticks=[])
    ax.text(
        0.99,
        0.01,
        "UMAP: n_neighbors={}, min_dist={}".format(umap_object.n_neighbors,
                                                   umap_object.min_dist),
        transform=ax.transAxes,
        horizontalalignment="right",
        color=font_color,
    )

    return ax
コード例 #13
0
                           edgecolors="white",
                           linewidths=1)
    nx.draw_networkx_edges(graph, pos=pos, width=weights, alpha=0.1618, ax=ax)

plt.close()

nodes_py = [[name, a[0], a[1]] for name, a in zip(
    nodes,
    PCA(n_components=2, random_state=0).fit_transform(X_iris.loc[nodes]))]
ds_nodes = pd.DataFrame(nodes_py, columns=['name', 'x', 'y'])

ds_edges_py = [[int(n0.split("_")[1]),
                int(n1.split("_")[1])] for (n0, n1) in graph.edges]
ds_edges = pd.DataFrame(ds_edges_py, columns=['source', 'target'])

hb = hammer_bundle(ds_nodes, ds_edges)

# hb.plot(x="x", y="y", figsize=(9,9), zorder=0, linewidth=1, color='black', alpha=0.9)

plt.close()

with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots(figsize=(8, 8))
    ax.plot(hb.x, hb.y, 'y', zorder=0, linewidth=1, color='black', alpha=0.9)
    nx.draw_networkx_nodes(graph,
                           pos=pos,
                           node_color=c_iris[nodes],
                           ax=ax,
                           node_size=50,
                           edgecolors='white',
                           linewidths=1)
コード例 #14
0
def edge_bundle_plotly(
    graph, colors, tab10, segments=None, pos_=None,
    streamlit=False, just_nodes= True
):
    nodes = graph.nodes
    second = graph
    orig_pos = nx.get_node_attributes(second, "pos")
    nodes_ind = [i for i in range(0, len(graph.nodes()))]
    redo = {k: v for k, v in zip(graph.nodes, nodes_ind)}
    if pos_ is None:
        pos_ = nx.get_node_attributes(graph, "pos")

    #assert segments is not None

    #if segments is None:
    coords = []
    for node in graph.nodes:
        x, y = pos_[node]
        coords.append((x, y))
    nodes_py = [
        [new_name, pos[0], pos[1]]
        for name, pos, new_name in zip(nodes, coords, nodes_ind)
    ]
    ds_nodes = pd.DataFrame(nodes_py, columns=["name", "x", "y"])

    ds_edges_py = []
    for (n0, n1) in graph.edges:
        ds_edges_py.append([redo[n0], redo[n1]])

    ds_edges = pd.DataFrame(ds_edges_py, columns=["source", "target"])

    hb = hammer_bundle(ds_nodes, ds_edges)
    hbnp = hb.to_numpy()
    splits = (np.isnan(hbnp[:, 0])).nonzero()[0]
    start = 0

    segments = []
    for stop in splits:
        seg = hbnp[start:stop, :]
        segments.append(seg)
        start = stop
    #df_geo = pd.DataFrame(columns=["lat", "lon", "text", "size", "color"])
    #df_geo["lat"] = [i[1] for i in pos_.values()]
    #df_geo["lon"] = [i[0] for i in pos_.values()]
    #for name in graph.nodes:
    #    assert name in sirg_author_list
        #    print(name)
    #df_geo["text"] = list(node for node in graph.nodes)

    fig = go.Figure()
    lats = []
    lons = []
    traces = []
    other_traces = []
    #if streamlit:
    #    st.markdown(
    #        """Note only 1001 node edges are shown in interactive plot below, because making the full list of {0} edges interactive would take hours""".format(
    #            len(segments)
    #        )
    #    )
    if not just_nodes:
        for ind, seg in enumerate(tqdm(segments, title="Modifying Edges for Interactivity")):
            x0, y0 = seg[1, 0], seg[1, 1]  # graph.nodes[edge[0]]['pos']
            x1, y1 = seg[-1, 0], seg[-1, 1]  # graph.nodes[edge[1]]['pos']
            xx = seg[:, 0]
            yy = seg[:, 1]
            lats.append(xx)
            lons.append(yy)
            for i, j in enumerate(xx):
                if i > 0:
                    other_traces.append(
                        go.Scattergeo(
                            lon=[xx[i], xx[i - 1]],
                            lat=[yy[i], yy[i - 1]],
                            mode="lines",
                            showlegend=False,
                            hoverinfo='skip',
                            line=dict(width=0.5, color="blue"),
                        )
                    )
        fig.add_traces(other_traces)

    #with open('expensive_plotly_traces.p','wb') as f:
    #    pickle.dump(other_traces,f)
    fig.add_trace(
        go.Scattergeo(
            lat=df_geo["lat"],
            lon=df_geo["lon"],
            marker=dict(
                size=3,  # data['Confirmed-ref'],
                color=colors,
                opacity=1,
            ),
            text=list(graph.nodes),
            hovertemplate="%{text} <extra></extra>",
        )
    )
    # layout = fig["layout"]
    if streamlit:
        fig["layout"]["width"] = 1825
        fig["layout"]["height"] = 1825
        st.write(fig)
    return fig,colors