Example #1
0
def create_network_graph(p1, p2):
    files = glob.glob('static/images/*_network_graph.png')
    for f in files:
        os.remove(f)

    p_graph = nx.read_gpickle(f'../data/combined_graphs/{p1}/{p2}.gpickle')

    chapter_names = pickle.load(open('../data/chapter_names.p', 'rb'))
    spa_dictionary = Dictionary.load('../data/spa.dict')
    syn_dictionary = Dictionary.load('../data/syn.dict')

    for node, data in p_graph.nodes(data=True):
        # it's a synonym node
        if data['type'] == 'SYN':
            data['document'] = 'Synonym'
            data['term'] = syn_dictionary[data['term_id']]

        else:
            data['document'] = chapter_names[data['doc_id']]
            data['term'] = spa_dictionary[data['term_id']]

    p_graph = nx.relabel_nodes(
        p_graph,
        {node: f"{node}: {data['term']}" for node, data in p_graph.nodes(data=True)}
    )

    ap = nv.CircosPlot(
        p_graph,
        node_color='doc_id',
        node_grouping='document',
        group_label_position='middle',
        group_label_color=True,
        node_labels=True,
        node_label_layout="numbers",
        figsize=(10, 8)
    )

    ap.draw_group_labels()

    ap.draw()

    plt.savefig(f'./static/images/{p1}_{p2}_network_graph.png')
Example #2
0
    G.node[n]['degree'] = nx.degree(G)[n]


import nxviz as nv
import matplotlib.pyplot as plt

# Create the ArcPlot object: a
a = nv.ArcPlot(G, node_order='degree', node_labels=True)
a.draw()
ap = nv.ArcPlot(G, node_order='date', node_color='date', node_labels=True, node_size='date')
ap.draw()

h = nv.MatrixPlot(G)#, node_grouping='grouping')
h.draw()

c = nv.CircosPlot(G, node_order='degree', node_grouping = 'date', node_color='date')
c.draw()


###IDENTIFYING IMPORTANT NODES
list(G.neighbors(1))
nx.degree_centrality(G)
nx.betweenness_centrality(G)

# Define path_exists()
def path_exists(G, node1, node2):
    """
    This function checks whether a path exists between two nodes (node1, node2) in graph G.
    """
    visited_nodes = set()
    queue = [node1]
Example #3
0
def circos(df=DataFrame([]),
           label=True,
           node_color='None',
           column=1,
           inter=25,
           size=5,
           fontsize=10):
    df1 = df[['GO', 'Entry', 'Term',
              'Short_Term']].merge(df, on='Entry',
                                   how='left').drop_duplicates()
    df2 = DataFrame(df[['GO', 'Term', 'Short_Term',
                        'Entry']].drop_duplicates().groupby(
                            ['GO', 'Term',
                             'Short_Term']).Entry.count()).reset_index()
    #### >>>>>>>>>>>>>>>>
    #### A partir de una matriz de datos extrae valores no redundantes
    matrix = df1.pivot_table(values='Entry',
                             index=['GO_x', 'Term_x', 'Short_Term_x'],
                             aggfunc=len,
                             columns=['GO_y', 'Term_y', 'Short_Term_y'])
    ###
    df_mat = []
    n = -1
    for i in list(matrix.columns.values):
        n += 1
        new = DataFrame(matrix.iloc[n:len(matrix)][i])
        nn = -1
        for index, row in new.iterrows():
            nn += 1
            df_mat.append([index, i, new.iloc[nn][i]])
        nn = 0
    ###
    df_mat = DataFrame(df_mat, columns=['go0', 'go1', 'val']).dropna()
    ###
    nodos = []
    for index, row in df_mat.iterrows():
        if row.go0 == row.go1:
            #print(row.go0, row.go1)
            continue
        else:
            #print(row.go0, row.go1)
            nodos.append([row.go0, row.go1, row.val])
    nodos = DataFrame(nodos)
    columnas = {0: 'GO', 1: 'Term', 2: 'Short_Term'}
    nodos = DataFrame([[i[column] for i in nodos[0]],
                       [i[column] for i in nodos[1]], nodos[2] / 2]).T
    #### >>>>>>>>>>>>>>>>
    # si interacciona con mas uno, eliminar la redundancia, y si no interacciona con ninguno, dejar el nodo
    # y su valor, este se verĂ¡ en la red como un nodo aislado
    aislado = [i for i in matrix.columns if len(matrix[[i]].dropna()) == 1]
    aislado = [df_mat[df_mat.go0 == i] for i in aislado]
    if len(aislado) > 0:
        aislado = pd.concat(aislado)
        aislado.columns = [0, 1, 2]
        aislado = DataFrame([[i[column] for i in aislado[0]],
                             [i[column] for i in aislado[1]],
                             aislado[2] / 2]).T
        nodos = pd.concat([nodos, aislado])
    else:
        pass
    nodos.columns = ['Source', 'Target', 'Weight']
    edges = nodos

    order = []
    for index, row in nodos.iterrows():
        order.append(row[0])
        order.append(row[1])
    orden3 = DataFrame(order).drop_duplicates(keep='first').reset_index(
        drop=True)
    orden3.columns = [columnas[column]]
    nodes = pd.merge(orden3, df2, on=[columnas[column]], how='left')

    def make_graph(nodes, edges):
        g = nx.Graph()

        for i, row in nodes.iterrows():
            keys = row.index.tolist()
            values = row.values
            # The dict contains all attributes
            g.add_node(row[nodes.columns[0]], **dict(zip(keys, values)))

        for i, row in edges.iterrows():
            keys = row.index.tolist()
            values = row.values
            g.add_edge(row['Source'], row['Target'], **dict(zip(keys, values)))
        return g

    g = make_graph(nodes, edges)
    for i, row in nodes.iterrows():
        if row['Entry'] >= inter:
            g.add_node(row[nodes.columns[0]], umbral='up')
        if row['Entry'] < inter:
            g.add_node(row[nodes.columns[0]], umbral='down')
    color_nodo = {
        'Uniques': nodes.columns[0],
        'Umbral': 'umbral',
        'None': False
    }
    c = nxv.CircosPlot(
        g,
        node_color=color_nodo[node_color],  # nodes.columns[0],
        node_grouping=color_nodo[node_color],
        node_labels=label,
        node_label_layout='rotation',
        edge_width='Weight',
        #edge_color = 'umbral',
        figsize=(size, size),
        fontsize=fontsize)
    return c.draw()
Example #4
0
# - Directed : Twitter
# 3. networkx : API for analysis of Graph
# 4. nxviz : API for creating beautiful and rational graph viz

import networkx as nx
G.nodes()
G.edges()
len(G.nodes())
len(G.edges())

type(G) #Check type of Graph

import nxviz as nv 
import matplotlib.pyplot as plt

c = nv.CircosPlot(G)
c.draw()
plt.show()

############################# Task 1 (Exploratory data analysis)
type(G)
len(G.nodes())
len(G.edges())

############################ Task 2 (Plotting using nxviz)
# Create the CircosPlot object: c
c = CircosPlot(G,node_color='bipartite',node_grouping='bipartite',node_order='centrality')

# Draw c to the screen
c.draw()
Example #5
0
def nxvizPlot(
    adata,
    cluster,
    cluster_name,
    edges_list,
    plot="arcplot",
    network=None,
    weight_scale=5e3,
    weight_threshold=1e-4,
    figsize=(6, 6),
    save_show_or_return="show",
    save_kwargs={},
    **kwargs,
):
    """Arc or circos plot of gene regulatory network for a particular cell cluster.

    Parameters
    ----------
        adata: :class:`~anndata.AnnData`.
            AnnData object.
        cluster: `str`
            The group key that points to the columns of `adata.obs`.
        cluster_name: `str` (default: `None`)
            The group whose network and arcplot will be constructed and created.
        edges_list: `dict` of `pandas.DataFrame`
            A dictionary of dataframe of interactions between input genes for each group of cells based on ranking
            information of Jacobian analysis. Each composite dataframe has `regulator`, `target` and `weight` three
            columns.
        plot: `str` (default: `arcplot`)
            Which nxviz plot to use, one of {'arcplot', 'circosplot'}.
        network: class:`~networkx.classes.digraph.DiGraph`
            A direct network for this cluster constructed based on Jacobian analysis.
        weight_scale: `float` (default: `1e3`)
            Because values in Jacobian matrix is often small, the value will be multiplied by the weight_scale so that
            the edge will have proper width in display.
        weight_threshold: `float` (default: `weight_threshold`)
            The threshold of weight that will be used to trim the edges for network reconstruction.
        figsize: `None` or `[float, float]` (default: (6, 6)
            The width and height of each panel in the figure.
        save_show_or_return: `str` {'save', 'show', 'return'} (default: `show`)
            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": 'arcplot', "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.
        **kwargs:
            Additional parameters that will pass to ArcPlot or CircosPlot

    Returns
    -------
        Nothing but plot an ArcPlot of the input direct network.
    """

    _, has_labeling = (
        adata.uns["pp"].get("has_splicing"),
        adata.uns["pp"].get("has_labeling"),
    )
    layer = "M_s" if not has_labeling else "M_t"

    import matplotlib.pyplot as plt

    try:
        import networkx as nx
        import nxviz as nv
    except ImportError:
        raise ImportError(
            "You need to install the packages `networkx, nxviz`."
            "install networkx via `pip install networkx`."
            "install nxviz via `pip install nxviz`."
        )

    if edges_list is not None:
        network = nx.from_pandas_edgelist(
            edges_list[cluster_name].query("weight > @weight_threshold"),
            "regulator",
            "target",
            edge_attr="weight",
            create_using=nx.DiGraph(),
        )
        if len(network.node) == 0:
            raise ValueError(
                f"weight_threshold is too high, no edge has weight than {weight_threshold} " f"for cluster {cluster}."
            )

    # Iterate over all the nodes in G, including the metadata
    if type(cluster_name) is str:
        cluster_names = [cluster_name]
    for n, d in network.nodes(data=True):
        # Calculate the degree of each node: G.node[n]['degree']
        network.nodes[n]["degree"] = nx.degree(network, n)
        # data has to be float
        if cluster is not None:
            network.nodes[n]["size"] = (
                adata[adata.obs[cluster].isin(cluster_names), n].layers[layer].A.mean().astype(float)
            )
        else:
            network.nodes[n]["size"] = adata[:, n].layers[layer].A.mean().astype(float)

        network.nodes[n]["label"] = n
    for e in network.edges():
        network.edges[e]["weight"] *= weight_scale

    if plot.lower() == "arcplot":
        prefix = "arcPlot"
        # Create the customized ArcPlot object: a2
        nv_ax = nv.ArcPlot(
            network,
            node_order=kwargs.pop("node_order", "degree"),
            node_size=kwargs.pop("node_size", None),
            node_grouping=kwargs.pop("node_grouping", None),
            group_order=kwargs.pop("group_order", "alphabetically"),
            node_color=kwargs.pop("node_color", "size"),
            node_labels=kwargs.pop("node_labels", True),
            edge_width=kwargs.pop("edge_width", "weight"),
            edge_color=kwargs.pop("edge_color", None),
            data_types=kwargs.pop("data_types", None),
            nodeprops=kwargs.pop(
                "nodeprops",
                {
                    "facecolor": "None",
                    "alpha": 0.2,
                    "cmap": "viridis",
                    "label": "label",
                },
            ),
            edgeprops=kwargs.pop("edgeprops", {"facecolor": "None", "alpha": 0.2}),
            node_label_color=kwargs.pop("node_label_color", False),
            group_label_position=kwargs.pop("group_label_position", None),
            group_label_color=kwargs.pop("group_label_color", False),
            fontsize=kwargs.pop("fontsize", 10),
            fontfamily=kwargs.pop("fontfamily", "serif"),
            figsize=figsize,
        )
    elif plot.lower() == "circosplot":
        prefix = "circosPlot"
        # Create the customized CircosPlot object: a2
        nv_ax = nv.CircosPlot(
            network,
            node_order=kwargs.pop("node_order", "degree"),
            node_size=kwargs.pop("node_size", None),
            node_grouping=kwargs.pop("node_grouping", None),
            group_order=kwargs.pop("group_order", "alphabetically"),
            node_color=kwargs.pop("node_color", "size"),
            node_labels=kwargs.pop("node_labels", True),
            edge_width=kwargs.pop("edge_width", "weight"),
            edge_color=kwargs.pop("edge_color", None),
            data_types=kwargs.pop("data_types", None),
            nodeprops=kwargs.pop("nodeprops", None),
            node_label_layout="rotation",
            edgeprops=kwargs.pop("edgeprops", {"facecolor": "None", "alpha": 0.2}),
            node_label_color=kwargs.pop("node_label_color", False),
            group_label_position=kwargs.pop("group_label_position", None),
            group_label_color=kwargs.pop("group_label_color", False),
            fontsize=kwargs.pop("fontsize", 10),
            fontfamily=kwargs.pop("fontfamily", "serif"),
            figsize=figsize,
        )

    # recover network edge weights
    for e in network.edges():
        network.edges[e]["weight"] /= weight_scale

    if save_show_or_return == "save":
        # Draw a to the screen
        nv_ax.draw()
        plt.autoscale()
        s_kwargs = {
            "path": None,
            "prefix": prefix,
            "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":
        # Draw a to the screen
        nv_ax.draw()
        plt.autoscale()
        # Display the plot
        plt.show()
        # plt.savefig('./unknown_arcplot.pdf', dpi=300)
    elif save_show_or_return == "return":
        return nv_ax
Example #6
0
plt.clf()

nx.draw_spectral(G, with_labels=True)
plt.pause(2)
plt.close()


for n, d in G.nodes(data=True):

    # Calculate the degree of each node: G.node[n]['degree']
    G.node[n]['degree'] = nx.degree(G, n)

circ = nv.CircosPlot(G, node_order='degree',
                     node_grouping='grouping',
                     node_color='gender',
                        node_labels=True,
                     # ["beginning", "middle", "end"]
                    #  group_label_position="beginning",
                        group_label_color=True
                         )

circ.draw()
plt.show() 





import os
import networkx as nx
import nxviz as nv
import pickle as plk
Example #7
0
def clone_overlap(self: Union[AnnData, Dandelion],
                  groupby: str,
                  colorby: str,
                  min_clone_size: Union[None, int] = None,
                  clone_key: Union[None, str] = None,
                  color_mapping: Union[None, Sequence, Dict] = None,
                  node_labels: bool = True,
                  node_label_layout: Literal[None, 'rotation',
                                             'numbers'] = 'rotation',
                  group_label_position: Literal['beginning', 'middle',
                                                'end'] = 'middle',
                  group_label_offset: int = 8,
                  figsize: Tuple[Union[int, float], Union[int,
                                                          float]] = (8, 8),
                  return_graph: bool = False,
                  save: Union[None, str] = None,
                  **kwargs):
    """
    A plot function to visualise clonal overlap as a circos-style plot. Requires nxviz.

    Parameters
    ----------
    self : Dandelion, AnnData
        `Dandelion` or `AnnData` object.
    groupby : str
        column name in obs/metadata for collapsing to nodes in circos plot.
    colorby : str
        column name in obs/metadata for grouping and color of nodes in circos plot.
    min_clone_size : int, optional
        minimum size of clone for plotting connections. Defaults to 2 if left as None.
    clone_key : str, optional
        column name for clones. None defaults to 'clone_id'.
    color_maopping : Dict, Sequence, optional
        custom color mapping provided as a sequence (correpsonding to order of categories or alpha-numeric order if dtype is not category), or dictionary containing custom {category:color} mapping.
    node_labels : bool, optional
        whether to use node objects as labels or not
    node_label_layout : bool, optional
        which/whether (a) node layout is used. One of 'rotation', 'numbers' or None.
    group_label_position : str
        The position of the group label. One of 'beginning', 'middle' or 'end'.
    group_label_offset : int, float
        how much to offset the group labels, so that they are not overlapping with node labels.
    figsize : Tuple[Union[int,float], Union[int,float]]
        figure size. Default is (8, 8).
    return_graph : bool
        whether or not to return the graph for fine tuning. Default is False.
    **kwargs
        passed to `matplotlib.pyplot.savefig`.

    Returns
    -------
    a `nxviz.CircosPlot`.
    """
    import networkx as nx
    try:
        import nxviz as nxv
    except:
        raise (ImportError(
            "Unable to import module `nxviz`. Have you done install nxviz? Try pip install git+https://github.com/zktuong/nxviz.git"
        ))

    if min_clone_size is None:
        min_size = 2
    else:
        min_size = int(min_clone_size)

    if clone_key is None:
        clone_ = 'clone_id'
    else:
        clone_ = clone_key

    if self.__class__ == AnnData:
        data = self.obs.copy()
        # get rid of problematic rows that appear because of category conversion?
        data = data[~(data[clone_].isin(
            [np.nan, 'nan', 'NaN', 'No_contig', 'unassigned', None]))]
        if 'clone_overlap' in self.uns:
            overlap = self.uns['clone_overlap'].copy()
        else:
            # prepare a summary table
            datc_ = data[clone_].str.split('|', expand=True).stack()
            datc_ = pd.DataFrame(datc_)
            datc_.reset_index(drop=False, inplace=True)
            datc_.columns = ['cell_id', 'tmp', clone_]
            datc_.drop('tmp', inplace=True, axis=1)
            datc_ = datc_[~(datc_[clone_].isin(
                ['', np.nan, 'nan', 'NaN', 'No_contig', 'unassigned', None]))]
            dictg_ = dict(data[groupby])
            datc_[groupby] = [dictg_[l] for l in datc_['cell_id']]

            overlap = pd.crosstab(data[clone_], data[groupby])

            if min_size == 0:
                raise ValueError('min_size must be greater than 0.')
            elif min_size > 2:
                overlap[overlap < min_size] = 0
                overlap[overlap >= min_size] = 1
            elif min_size == 2:
                overlap[overlap >= min_size] = 1

            overlap.index.name = None
            overlap.columns.name = None
    elif self.__class__ == Dandelion:
        data = self.metadata.copy()
        # get rid of problematic rows that appear because of category conversion?
        data = data[~(data[clone_].isin(
            [np.nan, 'nan', 'NaN', 'No_contig', 'unassigned', None]))]

        # prepare a summary table
        datc_ = data[clone_].str.split('|', expand=True).stack()
        datc_ = pd.DataFrame(datc_)
        datc_.reset_index(drop=False, inplace=True)
        datc_.columns = ['cell_id', 'tmp', clone_]
        datc_.drop('tmp', inplace=True, axis=1)
        dictg_ = dict(data[groupby])
        datc_[groupby] = [dictg_[l] for l in datc_['cell_id']]

        overlap = pd.crosstab(data[clone_], data[groupby])

        if min_size == 0:
            raise ValueError('min_size must be greater than 0.')
        elif min_size > 2:
            overlap[overlap < min_size] = 0
            overlap[overlap >= min_size] = 1
        elif min_size == 2:
            overlap[overlap >= min_size] = 1

        overlap.index.name = None
        overlap.columns.name = None

    edges = {}
    for x in overlap.index:
        if overlap.loc[x].sum() > 1:
            edges[x] = [
                y + ({
                    str(clone_): x
                }, ) for y in list(
                    combinations(
                        [i for i in overlap.loc[x][overlap.loc[x] == 1].index],
                        2))
            ]

    # create graph
    G = nx.Graph()
    # add in the nodes
    G.add_nodes_from([(p, {
        str(colorby): d
    }) for p, d in zip(data[groupby], data[colorby])])

    # unpack the edgelist and add to the graph
    for edge in edges:
        G.add_edges_from(edges[edge])
    groupby_dict = dict(zip(data[groupby], data[colorby]))
    if color_mapping is None:
        if self.__class__ == AnnData:
            if pd.api.types.is_categorical_dtype(self.obs[groupby]):
                try:
                    colorby_dict = dict(
                        zip(list(self.obs[str(colorby)].cat.categories),
                            self.uns[str(colorby) + '_colors']))
                except:
                    pass
    else:
        if type(color_mapping) is dict:
            colorby_dict = color_mapping
        else:
            if pd.api.types.is_categorical_dtype(data[groupby]):
                colorby_dict = dict(
                    zip(list(data[str(colorby)].cat.categories),
                        color_mapping))
            else:
                colorby_dict = dict(
                    zip(sorted(list(set(data[str(colorby)]))), color_mapping))
    df = data[[groupby, colorby]]
    if groupby == colorby:
        df = data[[groupby]]
        df = df.sort_values(groupby).drop_duplicates(
            subset=groupby, keep="first").reset_index(drop=True)
    else:
        df = df.sort_values(colorby).drop_duplicates(
            subset=groupby, keep="first").reset_index(drop=True)

    c = nxv.CircosPlot(G,
                       node_color=colorby,
                       node_grouping=colorby,
                       node_labels=node_labels,
                       node_label_layout=node_label_layout,
                       group_label_position=group_label_position,
                       group_label_offset=group_label_offset,
                       figsize=figsize)
    c.nodes = list(df[groupby])
    if 'colorby_dict' in locals():
        c.node_colors = [colorby_dict[groupby_dict[c]] for c in c.nodes]
    c.compute_group_label_positions()
    c.compute_group_colors()
    c.draw()
    if save is not None:
        plt.savefig(save, bbox_inches='tight', **kwargs)
    if return_graph:
        return (c)
Example #8
0
                             'recipient1',
                             edge_attr=['date', 'subject'])
plot = nv.ArcPlot(G)
plot.draw()
plt.show()

# We can see our 500 nodes (employees) at the bottom and the dominance of the one node on the right side.  Please bear in mind, of course, that I am taking the first 500 rows of a 517,000 row dataset here, so we are only looking at emails from one of the 150 Enron executives contained in the full dataset.
#
# Next we'll bend the ends of this plot and join them together to form a circle, otherwise known as a
#
# CircosPlot
# ----------

# In[ ]:

plot = nv.CircosPlot(G)
plot.draw()
plt.show()

# Same deal here, although in my opinion a lot clearer and easier to comprehend.
#
# Still, this leaves a lot to be desired. It just doesn't *look* like what most folks expect from a network graph. So next we will use nxviz to
#
# Draw the Network
# ----------------

# In[ ]:

plt.figure(figsize=(20, 20))
pos = nx.spring_layout(G, k=.1)
nx.draw_networkx(G,
Example #9
0
plt.subplot(223)
nx.draw_circular(Gd,
                 with_labels=True,
                 node_size=nodesizeHub,
                 node_color=nodecolorHub,
                 cmap="coolwarm")

plt.title('Showing the HITS Hub scores')

# plt.show()
plt.subplot(224)
nx.draw_spectral(Gd,
                 with_labels=True,
                 node_size=nodesizeHub,
                 node_color=nodecolorHub,
                 cmap="coolwarm")

plt.title('Showing the HITS Hub scores')

circ = nv.CircosPlot(Gd,
                     node_labels=True,
                     node_order="Auth",
                     node_color="Auth",
                     node_size='nodesizeAuth')
circ.draw()
plt.title('Showing the HITS Authority scores')
plt.show()

print(Gd.nodes['A'])
print(nodesizeAuth)
Example #10
0
# Creating the correlation DataFrame
cor = pd.DataFrame.from_records(measures)
cor_T = cor.transpose()
# Calculating the correlation
cor_T.corr()

# Finding the most important character in the fifth book,
# according to degree centrality, betweenness centrality and pagerank.
p_rank, b_cent, d_cent = cor.idxmax(axis=1)

# Printing out the top character accoding to the three measures
print(p_rank, b_cent, d_cent)

#bk = books
#bk = nx.barbell_graph(m1=5,m2=1)
#nx.find_cliques(bk) ; plt.show()

G = nx.erdos_renyi_graph(n=20, p=0.2)
len(G)
len(G.edges())
len(G.nodes())
circ = nv.CircosPlot(G, node_color='key', node_group='key')
circ.draw()
#bk.nodes()
#nodes = bk.neighbors(8)
#G_eight = bk.subgraph(nodes)
#nx.draw(G_eight, with_labels=True)
#plt.savefig("GOT_Network")
#plt.show()
Example #11
0
# Network visualization ------------------------------------------------------------------------------------------------
# Matrix plot
m = nv.MatrixPlot(T)
m.draw()
plt.show()
# Convert T to a matrix format: A
A = nx.to_numpy_matrix(T)
# Convert A back to the NetworkX form as a directed graph: T_conv
T_conv = nx.from_numpy_matrix(A, create_using=nx.DiGraph())
# Check that the `category` metadata field is lost from each node
for n, d in T_conv.nodes(data=True):
    assert 'category' not in d.keys()

# Circos plot
c = nv.CircosPlot(T)
c.draw()
plt.show()

# Arc plot
a = ArcPlot(T, node_order='category', node_color='category')
a.draw()
plt.show()


# Important nodes ------------------------------------------------------------------------------------------------------
# The number of neighbors that a node has is called its "degree".
# Degree centrality = (no. neighbours) / (no. all possible neighbours) -> N if self-loops allowed, N-1 otherwise

# Get number of neighbours of node 1
T.neighbors(1)
Example #12
0
# plt.show()

nodes = pd.read_csv('got-s7-nodes.csv', index_col=1)
edges = pd.read_csv('got-s7-edges.csv')
g = make_graph(nodes, edges)

nx.draw(g, with_labels=True, edge_color='black')
print(g.nodes)
print(g.edges)

"""Node link diagram :
The nodes are shown as a jumbled mess with too much overlap.
"""

c = nxv.CircosPlot(g,
                   edge_width=(edges['Weight'] / edges['Weight'].quantile(0.97)).tolist(),
                   node_labels=True, node_label_layout='rotation',
  ) 
c.draw()

"""Circos plot which is much easier to read."""

deg_cen = nx.degree_centrality(g)
nodes['deg_cen'] = nodes['Id'].apply(lambda x: deg_cen[x])
g = make_graph(nodes, edges)

fig, ax = plt.subplots(figsize=(20,8))
sns.barplot(data=nodes.nlargest(50, 'deg_cen'), 
            x='Id', y='deg_cen', 
            ax=ax);
ax.set_xticklabels(ax.get_xticklabels(), rotation=90);
Example #13
0
print(counts.groupby("type").sum())

pl = (ggplot(counts, aes(x="knocked", y="counts", fill="type")) + geom_col() +
      labs(x="", y="strong interactions") + coord_flip())
pl.save("figures/knockout_counts.svg", width=4, height=12)

graph = nx.from_pandas_edgelist(pos[pos.change.abs() > 1e-2], "knocked",
                                "genus", "change")

for idx, _ in graph.nodes(data=True):
    graph.node[idx]["degree"] = float(graph.degree(idx))
circos = nxviz.CircosPlot(
    graph,
    node_labels=True,
    rotate_labels=True,
    edge_cmap="bwr",
    edge_color="change",
    edge_limits=(-pos.change.abs().max(), pos.change.abs().max()),
    node_color="degree",
    figsize=(9, 7.5),
)
# circos.figure.set_dpi(200)
circos.draw()
plt.tight_layout(rect=[0.05, 0.15, 0.7, 0.8])
plt.savefig("figures/circos.svg")
plt.close()

ns = (ko[(ko.change.abs() > 1e-2) & (ko.knocked != ko.genus)].groupby(
    ["genus", "knocked"]).sample.count().reset_index())

pl = (ggplot(ns, aes(x="sample")) +
      geom_histogram(bins=32, fill="lightgray", color="black") +
Example #14
0
# https://stackoverflow.com/questions/53366634/how-to-set-edge-color-in-nxviz-arcplot
D = nx.DiGraph()
D.add_nodes_from([1, 2, 3])
D.add_edge(1, 2)
D.add_edge(2, 3)

m = nz.MatrixPlot(D)
m.draw()
plt.show()

a = nz.ArcPlot(D)
a.draw(
)  # here you can provide node_order and node_color which is provided in nodes metadata
plt.show()

c = nz.CircosPlot(D)
c.draw()
plt.show()
# %%

# to get the neighbours of the node
D = nx.DiGraph()
D.add_nodes_from([1, 2, 3])
D.add_edge(1, 2)
D.add_edge(2, 3)

list(D.neighbors(2))  # this is the directed graph

G = nx.Graph()
G.add_nodes_from([1, 2, 3])
G.add_edge(1, 2)
Example #15
0
import nxviz as nv
import networkx as nx
import matplotlib.pyplot as plt

G = nx.Graph()
G.add_nodes_from([1, 2, 3])
G.add_edge(1, 2)
G.add_edge(1, 3)
G.add_edges_from([(2, 3)])
nx.draw(G)

m = nv.MatrixPlot(G)
m.draw()

c = nv.CircosPlot(G, node_size=1, edge_width=10, node_labels=True)
c.draw()

a = nv.ArcPlot(G)
a.draw()

plt.show()