Esempio n. 1
0
        G.node[nodeid]['gender'] = gender_code[0]

    return G


G = load_crime_network()

# Annotate each node with connectivity score
for n in G.nodes():
    dcs = nx.degree_centrality(G)
    G.node[n]['connectivity'] = dcs[n]

# Make a CircosPlot of the bipartite graph
c = CircosPlot(
    G,
    node_grouping='bipartite',
    node_order='connectivity',
    node_color='bipartite',
)
c.draw()

# Make the "people" projection of the bipartite graph.
person_nodes = [n for n in G.nodes() if G.node[n]['bipartite'] == 'person']
pG = nx.bipartite.projection.projected_graph(G, person_nodes)

for n in pG.nodes():
    dcs = nx.degree_centrality(pG)
    pG.node[n]['connectivity'] = dcs[n]

c = CircosPlot(pG,
               node_grouping='gender',
               node_order='connectivity',
def createGraph():
    # read data from database
    conn = sqlite3.connect('temp.db')
    cursor = conn.cursor()

    df_author = []
    sql_jn = """
    SELECT journal_name
    FROM journal_list
    """
    for row in cursor.execute(sql_jn):
        jn = str(row[0])
        print(jn)

        sql_final = """
         SELECT {paper_country_temp}.paper_id, country_list.country_name
         FROM {paper_country_temp}
         INNER JOIN country_list ON country_list.country_id = {paper_country_temp}.country_id
         ;""".format(paper_country_temp='paper_country_' +
                     jn.replace(" ", "_"))

        df2 = pd.read_sql_query(sql_final, conn)
        gb = df2['country_name'].groupby([df2.paper_id
                                          ]).apply(list).reset_index()
        df_author.append(gb['country_name'].tolist())
    print('---------------')
    flatten = [item for elem in df_author for item in elem]
    conn.commit()
    conn.close()

    record_list = []

    # part 2 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    dict_country = {
        'the Netherlands': 'Netherlands',
        'The Netherlands': 'Netherlands',
        'Aero Engine (Group) Corporation of China': 'China',
        'PR China': 'China',
        'United States': 'USA',
        'United Kingdom': 'UK',
        "People's Republic of China": 'China',
        'Republic of Singapore': 'Singapore',
        'United States of America': 'USA',
        'P.R. China': 'China',
    }
    sns.set_style("white")

    authors_flat = [author for authors in flatten for author in authors]

    # Part 3 $$$$$$$$$$$$$$$$$$$$$$$$$$$
    # Extract author connections article_authors
    authors = flatten
    print('@@@@@@@@@@@@@@@@@@@@@@@@@@')
    print(type(authors))
    print('%%%%%%%%%%%%%%%%%%%%%%%%%%')
    author_connections = list(
        map(lambda x: list(combinations(x[::-1], 2)), authors))
    flat_connections = [
        item for sublist in author_connections for item in sublist
    ]
    print(len(flat_connections))
    # Create a dataframe with the connections
    df = pd.DataFrame(flat_connections, columns=["From", "To"])
    df['From'] = df['From'].replace(dict_country)
    df['To'] = df['To'].replace(dict_country)
    df = df[df['From'] != df['To']]
    print(df)
    # df.to_excel('1.xlsx')
    df_graph = df.groupby(["From", "To"]).size().reset_index()
    print(df_graph)
    # df_graph.to_excel('2.xlsx')
    df_graph.columns = ["From", "To", "Count"]
    print(df_graph)

    G = nx.from_pandas_edgelist(df_graph,
                                source="From",
                                target="To",
                                edge_attr="Count")

    # Limit to TOP 50 authors
    top50authors = pd.DataFrame.from_records(
        Counter(authors_flat).most_common(50), columns=["Name", "Count"])

    top50_nodes = (n for n in list(G.nodes())
                   if n in list(top50authors["Name"]))

    G_50 = G.subgraph(top50_nodes)

    for n in G_50.nodes():
        G_50.node[n]["publications"] = int(
            top50authors[top50authors["Name"] == n]["Count"])

    c = CircosPlot(
        G_50,
        dpi=600,
        node_grouping="publications",
        figsize=(20, 20),
        node_color="publications",
        node_labels=True,
    )
    c.draw()
    plt.show()

    # find path
    # paths = list(
    #     nx.all_shortest_paths(G, source="Xing Wang", target="Wen Li")
    # )
    # for path in paths:
    #     print(path)
    return c
Esempio n. 3
0
        G.node[nodeid]["gender"] = gender_code[0]

    return G


G = load_crime_network()

# Annotate each node with connectivity score
for n in G.nodes():
    dcs = nx.degree_centrality(G)
    G.node[n]["connectivity"] = dcs[n]

# Make a CircosPlot of the bipartite graph
c = CircosPlot(
    G,
    node_grouping="bipartite",
    node_order="connectivity",
    node_color="bipartite",
)
c.draw()

# Make the "people" projection of the bipartite graph.
person_nodes = [n for n in G.nodes() if G.node[n]["bipartite"] == "person"]
pG = nx.bipartite.projection.projected_graph(G, person_nodes)

for n in pG.nodes():
    dcs = nx.degree_centrality(pG)
    pG.node[n]["connectivity"] = dcs[n]

c = CircosPlot(pG,
               node_grouping="gender",
               node_order="connectivity",
Esempio n. 4
0
edge_list=[]

for i in range(aa11.shape[0]):
    node=i+1
    node_list.append(node)
for i in range(len(last_coor)):

    last_coor[i][0] += 1
    last_coor[i][1] += 1

    edge_list.append(last_coor[i])
G = nx.Graph()
G.add_nodes_from(node_list)
G.add_edges_from(edge_list)
color_list=["a", "b", "c", "d", "e"]
for n, d in G.nodes(data=True):
    G.node[n]["class"] = node_list[n-1]

c = CircosPlot(graph=G,node_labels=True,
    node_label_rotation=True,
    fontsize=30,
    group_legend=True,
    figsize=(7, 7),node_color="class")

c.draw()
plt.title("circular graph of top Nf discriminative features across all cross-validation runs".title())
plt.show()


#* *
Esempio n. 5
0
from random import choice

import matplotlib.pyplot as plt
import networkx as nx

from nxviz.plots import CircosPlot

G = nx.barbell_graph(m1=10, m2=3)
for n, d in G.nodes(data=True):
    G.node[n]['class'] = choice(['a', 'b', 'c', 'd', 'e'])
c = CircosPlot(G,
               node_grouping="class",
               node_color="class",
               node_order='class',
               node_labels=False,
               group_label_position="middle",
               group_label_color=True)
c.draw()
plt.show()
def create_circos(data,
                  source,
                  target,
                  edge_attr,
                  node_classes,
                  node_grouping,
                  edge_width,
                  edge_color,
                  legend_label,
                  legend_color,
                  legend_sort,
                  node2color,
                  figsize=(15, 15),
                  alpha=.5,
                  title=None,
                  group_label_offset=10,
                  legend_length=9,
                  **kwargs):
    """Create a circos plot with correlations"""

    # create nodes and edges
    G = nx.from_pandas_edgelist(data,
                                source=source,
                                target=target,
                                edge_attr=edge_attr)

    # classify a node
    for n, _ in G.nodes(data=True):
        G.nodes[n]["class"] = node_classes[n]

    # initialize Circos plot
    c = CircosPlot(G,
                   node_grouping=node_grouping,
                   edge_width=edge_width,
                   edge_color=edge_color,
                   figsize=figsize,
                   node_labels=True,
                   node_label_layout="rotation",
                   group_label_position=None,
                   group_label_color=True,
                   group_label_offset=group_label_offset,
                   **kwargs)

    # set alpha of edges
    c.edgeprops['alpha'] = alpha

    # set node colors
    node_colors = []
    for l in c.nodes:
        lc = l.split('(')[0].strip()
        co = node2color[lc]
        c_rgba = to_rgba(co)
        node_colors.append(c_rgba)
    c.node_colors = node_colors
    c.node_size = .5

    # set edge colors
    edge_colors = []
    for e in c.edges:
        try:
            ec = data.loc[(data[source] == e[0]) & (data[target] == e[1]),
                          legend_color]
            edge_color = ec.item()
        except ValueError:
            ec = data.loc[(data[source] == e[1]) & (data[target] == e[0]),
                          legend_color]
            edge_color = ec.item()
        except Exception as err:
            print(e)
            print(ec)
            raise err

        edge_colors.append(edge_color)
    c.edge_colors = edge_colors

    # actually draw the Circos plot
    c.draw()

    # get matplotlib.pyplot figure to add legend and title
    fig = c.figure

    # create legend for edge colors
    edge_legends, edge_labels = custom_legend(data=data,
                                              title='Edge colors',
                                              length=legend_length,
                                              label=legend_label,
                                              color=legend_color,
                                              sort_by=legend_sort,
                                              alpha=alpha)
    # create legend for node colors
    class2color = {}
    for k, v in node_classes.items():
        if k.startswith('UR_'): k = k.split('(')[0].strip()
        class2color[v] = node2color[k]

    node_legends, node_labels = custom_legend(data=class2color,
                                              length=legend_length,
                                              title='Node colors',
                                              alpha=alpha)

    # add legend
    fig.legend(handles=edge_legends + node_legends,
               labels=edge_labels + node_labels,
               ncol=2,
               loc='lower right')

    if title is not None:
        fig.suptitle(title, fontsize=16)

    plt.close(fig)

    return fig
Esempio n. 7
0
"""
Displays a NetworkX octahedral graph to screen using a CircosPlot.
"""

from nxviz.plots import CircosPlot
import networkx as nx
import matplotlib.pyplot as plt

G = nx.octahedral_graph()
c = CircosPlot(G.nodes(), G.edges(), plot_radius=5)
c.draw()
plt.show()
Esempio n. 8
0
    G = nx.Graph()
    G.add_edges_from(zip(df['doctor1'], df['doctor2']))

    return G


G = load_physicians_network()

# Make a CircosPlot, but with the nodes colored by their connected component
# subgraph ID.
ccs = nx.connected_component_subgraphs(G)
for i, g in enumerate(ccs):
    for n in g.nodes():
        G.node[n]['group'] = i
        G.node[n]['connectivity'] = G.degree(n)
m = CircosPlot(G,
               node_color='group',
               node_grouping='group',
               node_order='connectivity')
m.draw()
plt.show()

# Make an ArcPlot.
a = ArcPlot(G,
            node_color='group',
            node_grouping='group',
            node_order='connectivity')
a.draw()
plt.show()
Esempio n. 9
0
"""
Displays a NetworkX lollipop graph to screen using a CircosPlot.
"""

from nxviz.plots import CircosPlot
import numpy.random as npr
import networkx as nx
import matplotlib.pyplot as plt

G = nx.lollipop_graph(m=10, n=4)
for n, d in G.nodes(data=True):
    G.node[n]['value'] = npr.normal()
c = CircosPlot(G, node_color='value', node_order='value')
c.draw()
plt.show()
Esempio n. 10
0
plt.figure(figsize=(10, 7), dpi=150)
if type_plot == "classic":
    # Classic graphviz plot
    nx.draw(G,
            with_labels=True,
            node_shape="o",
            node_color=node_color,
            node_size=800,
            font_size=8)
elif type_plot == "nxviz":
    from nxviz.plots import CircosPlot as Plot

    c = Plot(
        G,
        node_color="value",
        node_order="value",
        node_labels=True,
        # , node_color=node_color
    )
    c.draw()
plt.tight_layout()
plt.savefig("graph.png")
plt.show()

try:
    import pygraphviz
    from networkx.drawing.nx_agraph import write_dot
    print("using package pygraphviz")
except ImportError:
    try:
        import pydot
Esempio n. 11
0
    G = nx.Graph()
    G.add_edges_from(zip(df["doctor1"], df["doctor2"]))

    return G


G = load_physicians_network()

# Make a CircosPlot, but with the nodes colored by their connected component
# subgraph ID.
ccs = nx.connected_component_subgraphs(G)
for i, g in enumerate(ccs):
    for n in g.nodes():
        G.node[n]["group"] = i
        G.node[n]["connectivity"] = G.degree(n)
m = CircosPlot(G,
               node_color="group",
               node_grouping="group",
               node_order="connectivity")
m.draw()
plt.show()

# Make an ArcPlot.
a = ArcPlot(G,
            node_color="group",
            node_grouping="group",
            node_order="connectivity")
a.draw()
plt.show()
Esempio n. 12
0
            continue
        recognize_counts[recognizing_tf] += 1

        G.add_node(target_tf, bipartite="target_tf", tf_fam=target_fam)
        G.add_node(recognizing_tf, bipartite="recognizing_tf", tf_fam=recognizing_fam)
        if target_tf != recognizing_tf:
            G.add_edge(target_tf, recognizing_tf, target_fam=target_fam, recognizing_fam=recognizing_fam)

    return G, recognize_counts

G,recognize_counts = load_motifs_network()
m = CircosPlot(
    G, node_grouping="tf_fam", node_color="tf_fam",
    group_label_position='middle', group_label_color=True,
    #, node_order="tf_fam"
    edge_color='target_fam',
    node_labels= lambda node: recognize_counts[node] >= 4,
    node_label_layout='rotation',
    fontsize=8,

)
m.compute_node_colors()
m.draw()
plt.show()


# # # Make an ArcPlot.
# a = ArcPlot(
#     G, node_color="tf_fam", node_grouping="tf_fam"#, node_order="connectivity"
# )
# a.draw()
# plt.show()
Esempio n. 13
0
    min_col += 1

g = nx.Graph(adj_matrix)
g = nx.relabel_nodes(g, nodes_idxs_rev)

for node in g.nodes():
    if node in nodes_g1:
        g.node[node]["class"] = "g1"
    if node in nodes_g2:
        g.node[node]["class"] = "g2"
    if node in nodes_g3:
        g.node[node]["class"] = "g3"

g = nx.relabel_nodes(g, term_names)

#c = CircosPlot(g, node_label_layout="numbers", dpi=800, fontsize=10,
#               node_color="class", node_grouping="class",
#               fig_size=(20,20), edge_width=weights, node_labels=True)
c = CircosPlot(g,
               dpi=800,
               fontsize=8,
               node_label_layout="numbers",
               node_color="class",
               node_grouping="class",
               fig_size=(20, 20),
               edge_width=weights,
               node_labels=True)
c.draw()
#plt.show()
plt.savefig("/home/wkg/Desktop/circos_test5.png", bbox_inches="tight", dpi=600)
Esempio n. 14
0
    ),
    "purple": ("Fortran", "P3DFFT"),
    "slategrey": ("CUDA", "cuFFT", "OpenMP", "MPI", "SIMD"),
}

G = read_adjlist(root / "dependency/graph.txt")
node_color = []
for node in G.nodes():
    color = [k for k, v in colors.items() if node in v]
    if color:
        # node_color.append(color[0])
        G.node[node]["value"] = color[0]
    else:
        raise ValueError("No color assigned for %s" % node)

#  nx.draw(G, with_labels=True, node_shape="s", node_color=node_color,
#          node_size=1000,)
from nxviz.plots import CircosPlot
c = CircosPlot(
    G,
    node_color="value",
    node_order="value",
    node_labels=True,
    # , node_color=node_color
    fontfamily="monospace",
)
c.draw()
plt.tight_layout()
plt.savefig(root / "dependency.pdf")
# plt.show()
def createGraphAuthor(user_year, input1):
    # read data from database
    conn = sqlite3.connect('temp.db')
    cursor = conn.cursor()
    year_list = list(range(user_year[0], user_year[1] + 1, 1))
    if len(year_list) == 1:
        year_list.append(year_list[0])
    df_author = []
    sql_jn = """
    SELECT journal_name
    FROM journal_list
    """
    for row in cursor.execute(sql_jn):
        jn = str(row[0])
        print(jn)

        sql_final = """
         SELECT {paper_author_temp}.paper_id, author_list.author_name
         FROM {paper_author_temp}
         INNER JOIN author_list ON author_list.author_id = {paper_author_temp}.author_id
         WHERE paper_id IN (SELECT paper_id
                     FROM {temp_paper_list}
                     WHERE paper_abstract LIKE '%{user_search_temp}%'
                     )
                     AND
                     paper_id IN (SELECT paper_id
                     FROM {temp_paper_list}
                     WHERE paper_year IN ( SELECT year_id
                     FROM year_list
                     WHERE year IN {temp_year}
                     ))
         ;""".format(paper_author_temp='paper_author_' + jn.replace(" ", "_"),
                     temp_paper_list='paper_list_' + jn.replace(" ", "_"),
                     user_search_temp=input1,
                     temp_year=str(tuple(year_list)))

        df2 = pd.read_sql_query(sql_final, conn)
        gb = df2['author_name'].groupby([df2.paper_id
                                         ]).apply(list).reset_index()
        df_author.append(gb['author_name'].tolist())
    print('---------------')
    flatten = [item for elem in df_author for item in elem]
    conn.commit()
    conn.close()

    record_list = []

    # part 2 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    sns.set_style("white")

    authors_flat = [author for authors in flatten for author in authors]

    # Part 3 $$$$$$$$$$$$$$$$$$$$$$$$$$$
    # Extract author connections article_authors
    authors = flatten
    print('@@@@@@@@@@@@@@@@@@@@@@@@@@')
    print(type(authors))
    print('%%%%%%%%%%%%%%%%%%%%%%%%%%')
    author_connections = list(
        map(lambda x: list(combinations(x[::-1], 2)), authors))
    flat_connections = [
        item for sublist in author_connections for item in sublist
    ]
    print(len(flat_connections))
    # Create a dataframe with the connections
    df = pd.DataFrame(flat_connections, columns=["From", "To"])
    print(df)
    # df.to_excel('1.xlsx')
    df_graph = df.groupby(["From", "To"]).size().reset_index()
    print(df_graph)
    # df_graph.to_excel('2.xlsx')
    df_graph.columns = ["From", "To", "Count"]
    print(df_graph)

    G = nx.from_pandas_edgelist(df_graph,
                                source="From",
                                target="To",
                                edge_attr="Count")

    # Limit to TOP 50 authors
    top50authors = pd.DataFrame.from_records(
        Counter(authors_flat).most_common(50), columns=["Name", "Count"])

    top50_nodes = (n for n in list(G.nodes())
                   if n in list(top50authors["Name"]))

    G_50 = G.subgraph(top50_nodes)

    for n in G_50.nodes():
        G_50.node[n]["publications"] = int(
            top50authors[top50authors["Name"] == n]["Count"])

    c = CircosPlot(
        G_50,
        dpi=600,
        node_grouping="publications",
        edge_width="Count",
        figsize=(20, 20),
        node_color="publications",
        node_labels=True,
    )
    m = c.draw()

    return m
import matplotlib.pyplot as plt
import networkx as nx
from nxviz.plots import CircosPlot

G = nx.barbell_graph(m1=10, m2=3)
for n, d in G.nodes(data=True):
    G.node[n]["class"] = choice(["a", "b", "c", "d", "e"])

c = CircosPlot(G,
               node_grouping="class",
               node_color="class",
               node_order="class",
               node_labels=True,
               node_label_rotation=True,
               node_label_color=True,
               group_label_color=True,
               node_label_layout='numbers',
               group_order='alphabetically',
               fontsize=10,
               group_legend=True,
               figsize=(12, 12))

# Draw the CircosPlot
c.draw()
c.figure.tight_layout()

# If you want more control over the legend, you can pass c.legend_handles
# to plt.legend()
plt.legend(handles=c.legend_handles,
           loc="upper center",
Esempio n. 17
0
"""
Shows how to rotate node labels. This increaes legibility for longer labels.
"""

import matplotlib.pyplot as plt
import networkx as nx

from nxviz.plots import CircosPlot

G = nx.barbell_graph(m1=20, m2=3)
# let's give the nodes some longer labels
G = nx.relabel_nodes(G,
                     {i: "long name #" + str(i) for i in range(len(G))}
                     )

# try it `rotate_labels=False` to see how the long names overlap each other
c = CircosPlot(G, node_labels=True, rotate_labels=True)
c.draw()
# the rotated labels take up more space, so we will have to increase the
# padding a bit. 15% on all sides works well here.
plt.tight_layout(rect=(0.15, 0.15, 0.85, 0.85))
plt.show()
Esempio n. 18
0
"""
Displays a NetworkX octahedral graph to screen using a CircosPlot.
"""

import matplotlib.pyplot as plt
import networkx as nx

from nxviz.plots import CircosPlot

G = nx.octahedral_graph()
c = CircosPlot(G)
c.draw()
plt.show()
Esempio n. 19
0
"""
Displays a NetworkX barbell graph to screen using a CircosPlot.
"""

from random import choice

import matplotlib.pyplot as plt
import networkx as nx

from nxviz.plots import CircosPlot

G = nx.barbell_graph(m1=10, m2=3)
for n, d in G.nodes(data=True):
    G.node[n]['class'] = choice(['one', 'two', 'three'])
c = CircosPlot(G, node_color="class", node_order='class', node_labels=True)
c.draw()
plt.show()
Esempio n. 20
0
pos = nx.spring_layout(G)  # positions for all nodes
# # First, draw nodes from table load
nx.draw_networkx_nodes(G, pos, nodelist=views, node_color='b')
nx.draw_networkx_nodes(G, pos, nodelist=tables, node_color='r')
nx.draw_networkx_edges(G, pos, edgelist=tl_edges, edge_color='b')
nx.draw_networkx_edges(G, pos, edgelist=vd_edges, edge_color='r')
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos)

# nx.draw_networkx_labels(G)
plt.show()

# some plots
#cpt = CircosPlot(graph=G, node_labels=True, node_color='label', edge_color='label')
#
cpt = CircosPlot(graph=G, node_labels=True, node_color='schema')
cpt.draw()
plt.show()

nx.draw_kamada_kawai(G)
# nx.draw_networkx_labels(G)
# nx.draw_networkx_edge_labels(G)
plt.show()
#  plt.savefig("path.png")

# schema_dc = nx.degree_centrality(G)
# G_undir=G.to_undirected()
# some_nodes = ['B', 'STG_C', 'C']
# G_ppt_nodes = G_undir.subgraph(some_nodes)

in_degrees_dict = dict(G.in_degree())
Esempio n. 21
0
from random import choice

import matplotlib.pyplot as plt
import networkx as nx

from nxviz.plots import CircosPlot

G = nx.barbell_graph(m1=10, m2=3)
for n, d in G.nodes(data=True):
    G.node[n]["class"] = choice(["a", "b", "c", "d", "e"])
c = CircosPlot(
    G,
    node_grouping="class",
    group_order="alphabetically",
    node_color="class",
    node_order="class",
    node_labels=False,
    group_label_position="middle",
    group_label_color=True,
)
c.draw()

d = CircosPlot(
    G,
    node_grouping="class",
    group_order="default",
    node_color="class",
    node_order="class",
    node_labels=False,
    group_label_position="middle",
    group_label_color=True,
Esempio n. 22
0
    ('a', 'c', {
        'class': 3
    }),
    ('b', 'd', {
        'class': 8
    }),
    ('c', 'd', {
        'class': 10
    }),
    ('e', 'd', {
        'class': 5
    }),
    ('e', 'f', {
        'class': 5
    }),
]

G = nx.Graph()
G.add_nodes_from(nodelist)
G.add_edges_from(edgelist1)
c = CircosPlot(graph=G, edge_color="weight")
c.draw()

F = nx.Graph()
F.add_nodes_from(nodelist)
F.add_edges_from(edgelist2)
d = CircosPlot(graph=F, edge_color="class")
d.draw()

plt.show()
Esempio n. 23
0
from random import choice

import matplotlib.pyplot as plt
import networkx as nx

from nxviz.plots import CircosPlot

G = nx.barbell_graph(m1=10, m2=3)
for n, d in G.nodes(data=True):
    G.node[n]["class"] = choice(["a", "b", "c", "d", "e"])
c = CircosPlot(
    G,
    node_grouping="class",
    node_color="class",
    node_order="class",
    node_labels=True,
    group_label_position="middle",
    group_label_color=True,
    group_label_offset=2,
)
c.draw()
plt.show()
Esempio n. 24
0
pos = nx.spring_layout(G)  # positions for all nodes
# # First, draw nodes from table load
nx.draw_networkx_nodes(G, pos, nodelist=tl_nodes, node_color='b')
nx.draw_networkx_nodes(G, pos, nodelist=vd_nodes, node_color='r')
nx.draw_networkx_edges(G, pos, edgelist=tl_edges, edge_color='b')
nx.draw_networkx_edges(G, pos, edgelist=vd_edges, edge_color='r')
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos)

# nx.draw_networkx_labels(G)
plt.show()

# some plots
#cpt = CircosPlot(graph=G, node_labels=True, node_color='label', edge_color='label')
#
cpt = CircosPlot(graph=G, node_labels=True)
cpt.draw()
plt.show()

nx.draw_kamada_kawai(G)
# nx.draw_networkx_labels(G)
# nx.draw_networkx_edge_labels(G)
plt.show()
#  plt.savefig("path.png")

# schema_dc = nx.degree_centrality(G)
# G_undir=G.to_undirected()
# some_nodes = ['B', 'STG_C', 'C']
# G_ppt_nodes = G_undir.subgraph(some_nodes)

in_degrees_dict = dict(G.in_degree())
Esempio n. 25
0
top50_nodes = (n for n in list(G.nodes()) if n in list(top50authors["Name"]))

G_50 = G.subgraph(top50_nodes)

for n in G_50.nodes():
    G_50.node[n]["publications"] = int(
        top50authors[top50authors["Name"] == n]["Count"]
    )


c = CircosPlot(
    G_50,
    dpi=600,
    node_grouping="publications",
    edge_width="Count",
    figsize=(20, 20),
    node_color="publications",
    node_labels=True,
)
c.draw()
plt.show()

## Network analysis
deg = nx.degree_centrality(G_50)
bet = nx.betweenness_centrality(G_50)

top_df = pd.DataFrame.from_dict(
    [deg, bet, dict(Counter(authors_flat).most_common(50))]
).T
top_df.columns = [
Esempio n. 26
0
"""
Shows different edge widths on CircusPlot
"""
import matplotlib.pyplot as plt
import networkx as nx
from nxviz.plots import CircosPlot

nodelist = [("a"), ("b"), ("c"), ("d"), ("e"), ("f")]
edgelist1 = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f")]

weights = list(range(6))

G = nx.Graph()
G.add_nodes_from(nodelist)
G.add_edges_from(edgelist1)
c = CircosPlot(graph=G, edge_width=weights)
c.draw()

plt.show()
Esempio n. 27
0
"""
Displays a NetworkX lollipop graph to screen using a CircosPlot.
"""

import matplotlib.pyplot as plt
import networkx as nx
import numpy.random as npr

from nxviz.plots import CircosPlot

G = nx.lollipop_graph(m=10, n=4)
for n, d in G.nodes(data=True):
    G.node[n]["value"] = npr.normal()
c = CircosPlot(G, node_color="value", node_order="value")
c.draw()
plt.show()
ws = rescale([float(G[u][v]['weight'])**70 for u, v in G.edges], 1, 50)
edgelist = [(str(u), str(v), {"weight": ws.pop(0)}) for u, v in G.edges]

# create new graph using nodelist and edgelist
g = nx.Graph(name='Protein Interaction Graph')
g.add_nodes_from(nodelist)
g.add_edges_from(edgelist)
# go through nodes in graph G and store their degree as "class" in graph g
for v in G:
    g.nodes[v]["class"] = G.degree(v)

#draw
c = CircosPlot(graph=g,
               figsize=(20, 20),
               node_grouping="class",
               node_color="class",
               edge_width="weight",
               node_labels=True,
               fontsize=10,
               fontfamily='sans-serif')  #,
##               group_label_offset=0.75,group_label_position='beginning',group_legend=True,
##               group_label_color=True)
c.figure.tight_layout()
c.draw()

#Get the label and color for each group used by nxviz
seen = set()
colors_group = [x for x in c.node_colors
                if not (x in seen or seen.add(x))]  #Gets colors in RGBA
labels_group = sorted(list(set([g.nodes[n][c.node_color] for n in G.nodes])))

#Create patchList to use as handle for plt.legend()
Esempio n. 29
0
"""
Displays a NetworkX barbell graph to screen using a CircosPlot.
"""

from nxviz.plots import CircosPlot
from random import choice
import networkx as nx
import matplotlib.pyplot as plt

G = nx.barbell_graph(m1=10, m2=3)
for n, d in G.nodes(data=True):
    G.node[n]['class'] = choice(['one', 'two', 'three'])
c = CircosPlot(G, node_color="class", node_order='class')
c.draw()
plt.show()