コード例 #1
0
def plot_time_after_spreading_vs_log_10_number_of_newly_infected_user(df):
    title = 'time (minutes) since seed creation time vs newly infected user {}'.format(
        project_name)
    number_of_seeds = 5
    seed_count_series = df.seed_index.value_counts()
    pallttes = sns.cubehelix_palette(number_of_seeds)

    for index in range(number_of_seeds):
        seed_index = seed_count_series.keys()[index]
        data_to_plot = df.copy()
        data_to_plot = data_to_plot[data_to_plot.seed_index ==
                                    seed_index]['time_since_seed']
        data_to_plot = data_to_plot.reset_index()
        data_to_plot['counter'] = np.log10(range(1, len(data_to_plot) + 1))
        plt.plot(data_to_plot['time_since_seed'],
                 data_to_plot['counter'],
                 marker='',
                 color=pallttes[number_of_seeds - index - 1],
                 linewidth=1,
                 alpha=0.9,
                 label='Seed {}'.format(index + 1))

    plt.title(title)
    plt.xlabel('time (minutes)')
    plt.ylabel('number of new infected users (log base 10)')
    plt.legend()
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #2
0
def plot_forward_bar(g, x):
    title = 'Forward spreading bar for seed at index {}'.format(x)
    plt.rcParams['figure.figsize'] = [15, 9]
    network = pd.DataFrame(
        data={
            'time_lapsed': list(
                nx.get_node_attributes(g, 'time_lapsed').values()),
            'generation': list(
                nx.get_node_attributes(g, 'generation').values())
        })

    depth = max(network.generation)
    d = pd.DataFrame(0,
                     index=np.arange(int(timeframe) / window),
                     columns=range(depth))
    for i in range(int(int(timeframe) / window)):
        data = network[(network.time_lapsed >= (i) * window)
                       & (network.time_lapsed < (i + 1) * window)]
        for generation in range(depth):
            d.iloc[i, generation] = sum(data.generation == generation)
    colors = get_colors(depth)
    ax = d.plot.bar(stacked=True, color=colors)
    ax.set_xticks(range(48))
    ax.set_xticklabels([i * 0.5 for i in range(48)])
    ax.set_xlabel('time lapsed (30 mins per bar)')
    ax.set_ylabel('number of newly infected users')
    patchList = []
    for index in range(depth):
        data_key = mpatches.Patch(color=colors[index],
                                  label='Generation {}'.format(index))
        patchList.append(data_key)
    plt.legend(handles=patchList)
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #3
0
def plot_time_vs_number_of_seeds(df):
    title = 'Time vs Number of seeds, for event {}'.format(project_name)
    seeds_dataframe = unique_users[unique_users.generation == 0].copy()
    seeds_dataframe = order_and_reindex(seeds_dataframe, 'time_lapsed')
    n_bins = math.floor(float(timeframe) / window)
    sns.distplot(seeds_dataframe['time_lapsed'], kde=False, bins=n_bins)
    plt.xlabel('time lapsed [{} minutes per bar]'.format(window))
    plt.ylabel('number of seeds')
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #4
0
def prob_dist_plot(graph):
    deg = dict(nx.degree(graph))
    x, y = zip(*Counter(deg.values()).items())
    plt.scatter(x, y, s=10, c="navy")
    plt.xscale("log")
    plt.yscale("log")
    plt.title("Tennis players degree distribution -- log scale")
    plt.xlim(0.9, max(x) + 10)
    plt.ylim(0.9, max(y) + 10)
    plt.xlabel("log(Degree)")
    plt.ylabel("log(Frequency)")
    dzcnapy.plot("Tennis players degree distribution")
コード例 #5
0
def plot_degree_frequency(network):
    title = 'Degree frequency of all nodes in the spreading of event {}'.format(
        project_name)
    deg = nx.degree(network_all)
    x, y = zip(*Counter(dict(deg).values()).items())
    plt.scatter(x, y)
    plt.xscale("log")
    plt.yscale("log")
    plt.xlim(0.9, max(x))
    plt.ylim(0.9, max(y))
    plt.xlabel("Degree")
    plt.ylabel("Frequency")
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #6
0
def plot_network(graph, title):
    plt.axis('off')
    pos = graphviz_layout(graph)
    nx.draw_networkx(graph, pos=pos, with_labels=False, **dzcnapy.small_attrs)
    depth = max(nx.get_node_attributes(graph, 'generation').values()) + 1
    colors = get_colors(depth)
    color = [colors[graph.node[n]["generation"]] for n in graph]
    dzcnapy.small_attrs["node_color"] = color
    patchList = []
    for index in range(depth):
        data_key = mpatches.Patch(color=colors[index],
                                  label='Generation {}'.format(index))
        patchList.append(data_key)
    plt.legend(handles=patchList)
    dzcnapy.set_extent(pos, plt)
    dzcnapy.plot(title, [15, 15], save=True)
コード例 #7
0
def plot_time_vs_log_seed_descedants(network):
    title = 'Time vs number of seed descendants for event {}'.format(
        project_name)
    seed_count_series = network.seed_index.value_counts()
    seeds_dataframe = unique_users[network.generation == 0].copy()
    seeds_dataframe['y'] = 0
    for index in seeds_dataframe.index:
        seeds_dataframe.loc[index, 'y'] = seed_count_series.get(index)
    # use the function regplot to make a scatterplot
    sns.regplot(x=seeds_dataframe["time_lapsed"],
                y=seeds_dataframe['y'],
                fit_reg=False)
    plt.xlabel('time lapsed (minutes)')
    plt.ylabel('number of descendants')
    plt.yscale("log")
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #8
0
def centrality_correlation_plot(centralities, cent1, cent2):
    X = cent1
    Y = cent2
    limits = pd.concat(
        [centralities[[X, Y]].min(), centralities[[X, Y]].max()],
        axis=1).values
    centralities.plot(kind="scatter",
                      x=X,
                      y=Y,
                      xlim=limits[0],
                      ylim=limits[1],
                      edgecolors='black',
                      color='pink',
                      s=75,
                      alpha=0.6)
    plt.grid()
    dzcnapy.plot("centralities_comparison")
コード例 #9
0
def plot_log_spreading_graph(df):
    title = 'Time versus total number of new infected users of the top 5 seeds during first 24 hours, for event {}'.format(
        project_name)
    number_of_seeds = 5
    seed_count_series = df.seed_index.value_counts()
    pallttes = sns.cubehelix_palette(number_of_seeds + 1)

    draw_dataframe = df.copy()
    draw_dataframe = draw_dataframe.filter(items=['time_lapsed'])
    draw_dataframe = draw_dataframe.reset_index()
    draw_dataframe['counter'] = range(1, len(draw_dataframe) + 1)
    plt.plot(draw_dataframe['time_lapsed'],
             draw_dataframe['counter'],
             marker='',
             color=pallttes[number_of_seeds],
             linewidth=1,
             alpha=0.9,
             label='all')

    for index in range(number_of_seeds):
        seed_index = seed_count_series.keys()[index]
        data_to_plot = df.copy()
        data_to_plot = data_to_plot[data_to_plot.seed_index ==
                                    seed_index]['time_lapsed']
        data_to_plot = data_to_plot.reset_index()
        data_to_plot['counter'] = range(1, len(data_to_plot) + 1)
        plt.plot(data_to_plot['time_lapsed'],
                 data_to_plot['counter'],
                 marker='',
                 color=pallttes[number_of_seeds - index],
                 linewidth=1,
                 alpha=0.9,
                 label='Seed {}'.format(index + 1))

    plt.xlabel('Time lapsed (minutes)')
    plt.ylabel('Total number of new infected users')
    plt.yscale("log")
    plt.legend()
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #10
0
def plot_time_lapsed_vs_newly_infected_users():
    title = 'time lapsed vs newly infected users for event {}'.format(
        project_name)
    d = pd.DataFrame(0,
                     index=np.arange(int(timeframe) / window),
                     columns=range(depth))
    for i in range(int(int(timeframe) / window)):
        data = unique_users[(unique_users.time_lapsed >= (i) * window)
                            & (unique_users.time_lapsed < (i + 1) * window)]
        for generation in range(depth):
            d.iloc[i, generation] = sum(data.generation == generation)
    colors = get_colors(depth)
    ax = d.plot.bar(stacked=True, color=colors)
    ax.set_xticks(range(48))
    ax.set_xticklabels([i * 0.5 for i in range(48)])
    ax.set_xlabel('time lapsed (30 mins per bar)')
    ax.set_ylabel('number of newly infected users')
    patchList = []
    for index in range(depth):
        data_key = mpatches.Patch(color=colors[index],
                                  label='Generation {}'.format(index))
        patchList.append(data_key)
    plt.legend(handles=patchList)
    dzcnapy.plot(title, [15, 9], save=True)
コード例 #11
0
generalized_network.remove_edges_from(generalized_network.selfloop_edges())

networks = {
    "generalized" : generalized_network,
    "pearson" : pearson_network_sign,
    "cosine" : cosine_network,
    "hamming" : hamming_network,
    }

partitions = [community.best_partition(x) for x in networks.values()]
statistics = sorted([
        (name,
         community.modularity(best_part, netw),
         len(set(best_part.values())),
         len(nx.isolates(netw))
         ) for (name, netw), best_part in zip(networks.items(), partitions)],
                    key=lambda x: x[1], reverse=True)
print(statistics)

pos = graphviz_layout(generalized_network)

for i, (name, _, _, _) in enumerate(statistics):
    net = networks[name]
    ax = plt.subplot(2, 2, i + 1)
    nx.draw_networkx_edges(net, pos, ax=ax, alpha=0.5, **dzcnapy.medium_attrs)
    nx.draw_networkx_nodes(net, pos, ax=ax, **dzcnapy.medium_attrs)
    nx.draw_networkx_labels(net, pos, ax=ax, **dzcnapy.medium_attrs)
    dzcnapy.set_extent(pos, ax, name)

dzcnapy.plot("compare_traumas")
コード例 #12
0
nhood = nx.subgraph(G, list(alters1.keys()) + [ego])
egonet = nx.ego_graph(G, ego)
pos = graphviz_layout(nhood)

#Locate the chord edges and remove them
chords = [(n1, n2) for n1, n2 in nhood.edges() if n1 != ego and n2 != ego]
nhood.remove_edges_from(chords)

#Draw the neighborhood and the ego-centric network
for g, ofile in zip((nhood, egonet), ("neighborhood", "egonet")):
    nx.draw_networkx_edges(g, pos, alpha=0.7, **dzcnapy.attrs)
    nx.draw_networkx_nodes(g, pos, **dzcnapy.attrs)
    nx.draw_networkx_labels(g, pos, alpha=0.7, **dzcnapy.medium_attrs)
    dzcnapy.set_extent(pos, plt)

    dzcnapy.plot(ofile)

F = nx.Graph(G)
deg = pd.Series(dict(nx.degree(G)))
cc = pd.Series({e: nx.clustering(F, e) for e in F})
deg_cc = pd.contact([deg, cc], axis=1)
deg_cc.columns = ("Degree", "CC")
deg_cc.groupby("Degree").mean().reset_index().plot(kind="scatter",
                                                   x="Degree",
                                                   y="CC",
                                                   s=100)
plt.xscale("log")
plt.ylim(ymin=0)
plt.grid()
dzcnapy.plot("deg_cc")
コード例 #13
0
import dzcnapy_plotlib as dzcnapy

F = nx.Graph()

for i in range(1, 9):
    for j,k in zip('ABCDEFG','BCDEFGH'):
        F.add_edge('{}{}'.format(j,i),'{}{}'.format(k,i))

for i in 'ABCDEFGH':
    for j,k in zip(range(1,8), range(2,9)):
        F.add_edge('{}{}'.format(i,j), '{}{}'.format(i,k))

pos = graphviz_layout(F)
nx.draw_networkx(F, pos, **dzcnapy.attrs)
dzcnapy.set_extent(pos, plt)
dzcnapy.plot("checkerboard")

#Tree
lincoln_list = [
    ("A.L.", "Edward Baker L."), ("A.L.", "Robert Todd L."), 
    ("A.L.", "William Wallace L."), ("A.L.", "Thomas L. III"),
    ("Jessie Harlan L.", "Mary L. Beckwith"), 
    ("Jessie Harlan L.", "Robert Todd L. Beckwith"), 
    ("Mary L.", "L. Isham"), ("Robert Todd L.", "A.L. II"), 
    ("Robert Todd L.", "Jessie Harlan L."), 
    ("Robert Todd L.", "Mary L."), ("Thomas L.", "A.L."), 
    ("Thomas L.", "Sarah L. Grigsby"), ("Thomas L.", "Thomas L. Jr."),
]
F = nx.DiGraph(lincoln_list)

pos = graphviz_layout(F)
コード例 #14
0
import networkx as nx, community, csv
import matplotlib.style as style, matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import graphviz_layout
import dzcnapy_plotlib as dzcnapy

F = nx.DiGraph()
F.add_node("C")
F.add_edges_from([("B", "b0"), ("b0", "b1"), ("b1", "B")])
F.add_edges_from([("A", "a0"), ("a0", "a1"), ("a1", "a2"), ("a1", "a3"), ("a3", "A")])

pos = graphviz_layout(F)
nx.draw_networkx(F, pos, **dzcnapy.attrs)
dzcnapy.set_extent(pos, plt)
dzcnapy.plot("abcNwtwork")

G = nx.Graph(
    (("Alpha", "Bravo"), ("Bravo", "Charlie"), ("Charlie", "Delta"),
     ("Charlie", "Echo"), ("Charlie", "Foxtrot"), ("Delta", "Echo"),
     ("Delta", "Foxtrot"), ("Echo", "Foxtrot"), ("Echo", "Golf"),
     ("Echo", "Hotel"), ("Foxtrot", "Golf"), ("Foxtrot", "Hotel"),
     ("Delta", "Hotel"), ("Golf", "Hotel"), ("Delta", "India"),
     ("Charlie", "India"), ("India", "Juliet"), ("Golf", "Kilo"),
     ("Alpha", "Kilo"), ("Bravo", "Lima")))
pos = graphviz_layout(G)
core = nx.k_core(G)
crust = nx.k_crust(G)
corona3 = nx.k_corona(G, k=3).nodes()
nx.draw_networkx(G, pos, nodelist=core, **dzcnapy.attrs)
nx.draw_networkx_edges(G, pos, core.edges(), **dzcnapy.tick_attrs)
nx.draw_networkx_edges(G, pos, crust.edges(), **dzcnapy.tick_attrs)
nx.draw_networkx_nodes(G, pos, crust, node_shape='v', **dzcnapy.attrs)
コード例 #15
0
    (58, 60, 132, 552, 291, 180, 88, 62, 58, 36, 20, 4, 3, 16, 119, 81),
    "Boston": (93, 104, 106, 101, 80, 82, 82, 110, 216, 292, 281, 205, 246,
               204, 159, 86),
    "Chicago": (115, 195, 122, 109, 86, 120, 157, 210, 273, 196, 139, 101, 113,
                106, 107, 115),
    "San Francisco":
    (35, 67, 156, 616, 1208, 894, 268, 67, 2, 0, 0, 0, 2, 9, 22, 35)
}

# Draw the wind roses
angles = np.linspace(0, 2 * np.pi, 16)
ax = plt.subplot(111, polar=True)
for name, wind in winds.items():
    ax.plot(angles, wind, "-o", label=name)
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
plt.legend(loc=2)
dzcnapy.plot("windroses")

wind_cities_cosine = pd.DataFrame(
    {y: [1 - dist.cosine(winds[x], winds[y]) for x in winds]
     for y in winds},
    index=winds.keys())

# Pearson correlation
wind_cities_pearson = pd.DataFrame(
    {y: [stats.pearsonr(winds[x], winds[y])[0] for x in winds]
     for y in winds},
    index=winds.keys())
pd.DataFrame(winds).corr()
コード例 #16
0
n_graph = bipartite.projected_graph(N, nutrients)
f_graph = bipartite.projected_graph(N, foods)

fw_graph = bipartite.weighted_projected_graph(N, foods, True)

# Edge width represents weights
dzcnapy.attrs["width"] = [d['weight'] * 75 for n1, n2, d in
                          fw_graph.edges(data=True)]
dzcnapy.thick_attrs["width"] = 10

pos = graphviz_layout(f_graph)
nx.draw_networkx_edges(f_graph, pos, **dzcnapy.thick_attrs)
nx.draw_networkx_nodes(f_graph, pos, **dzcnapy.attrs)
nx.draw_networkx_labels(f_graph, pos, **dzcnapy.attrs)
dzcnapy.set_extent(pos, plt)
dzcnapy.plot("projected_foods")

adj = bipartite.biadjacency_matrix(N, f_graph).toarray()
foods = pd.DataFrame([[stats.pearsonr(x, y)[0] for x in adj]
                      for y in adj], columns=f_graph, index=f_graph)

SLICING_THRESHOLD = 0.375
stacked = foods.stack()
edges = stacked[stacked >= SLICING_THRESHOLD].index.tolist()
f_pearson = nx.Graph(edges)

nx.draw_networkx_edges(f_pearson, pos, **dzcnapy.thick_attrs)
nx.draw_networkx_nodes(f_graph, pos, **dzcnapy.attrs)
nx.draw_networkx_labels(f_graph, pos, **dzcnapy.attrs)
dzcnapy.set_extent(pos, plt)
dzcnapy.plot("pearson_foods")
コード例 #17
0
    if nx.number_of_nodes(p) >= 20 or nx.number_of_edges(p) >= 20
]
panama0 = panama.subgraph(itertools.chain.from_iterable(components))

print(nx.number_of_nodes(panama0), nx.number_of_edges(panama0))

with open("panama-beneficiary.pickle", "wb") as outfile:
    pickle.dump(panama0, outfile)

cdict = {"Entities": "pink", "Officers": "blue", "Intermediaries": "green"}
c = [cdict[panama0.node[n]["kind"]] for n in panama0]
dzcnapy.small_attrs["node_color"] = c
pos = graphviz_layout(panama0)
nx.draw_networkx(panama0, pos=pos, with_labels=False, **dzcnapy.small_attrs)
dzcnapy.set_extent(pos, plt)
dzcnapy.plot("panama0")

nx.attribute_assortativity_coefficient(panama0, "kind")
nx.attribute_mixing_matrix(panama0,
                           "kind",
                           mapping={
                               "Entities": 0,
                               "Officers": 1,
                               "Intermediaries": 2
                           })
nx.attribute_assortativity_coefficient(panama0, "country")
nx.degree_assortativity_coefficient(panama0)

deg = nx.degree(panama0)
x, y = zip(*Counter(deg.values()).items())
コード例 #18
0
nx.set_node_attributes(G, nutrient_dict, "nutrient")

# Prepare for drawing
colors = ["yellow" if n[1]["nutrient"] else "pink" for n in
          G.nodes(data=True)]
dzcnapy.medium_attrs["node_color"] = colors

# Draw four layouts in four subplots
_, plot = plt.subplots(2, 2)

subplots = plot.reshape(1, 4)[0]
layouts = (nx.random_layout, nx.circular_layout, nx.spring_layout,
           nx.spectral_layout)
titles = ("Random", "Circular", "Force-Directed", "Spectral")
for plot, layout, title in zip(subplots, layouts, titles):
    pos = layout(G)
    nx.draw_networkx(G, pos=pos, ax=plot, with_labels=False, 
                     **dzcnapy.medium_attrs)
    plot.set_title(title)
    dzcnapy.set_extent(pos, plot)

dzcnapy.plot("nutrients")

from networkx.drawing.nx_agraph import graphviz_layout

_, plot = plt.subplots()
pos = graphviz_layout(G)
nx.draw_networkx(G, pos, **dzcnapy.attrs)
dzcnapy.set_extent(pos, plot)
dzcnapy.plot("nutrients-graphviz")
コード例 #19
0

def slice_network(G, T, copy=True):
    """
    Remove all edges with weight<T from G or its copy.
    """
    F = G.copy() if copy else G
    F.remove_edges_from(
        (n1, n2) for n1, n2, w in F.edges(data="weight") if w < T)
    return F


# Draw different degrees of slicing for a random graph
ergraph = nx.erdos_renyi_graph(100, 0.1)
nx.set_edge_attributes(ergraph, "weight", {(n1, n2): random.random()
                                           for n1, n2 in ergraph.edges()})

pos = graphviz_layout(ergraph)
for i, threshold in enumerate([0, 0.7, 0.8, 0.9, 0.95, 1.0]):
    ax = plt.subplot(3, 2, i + 1)
    slice_network(ergraph, threshold, copy=False)
    nx.draw_networkx_edges(ergraph,
                           pos,
                           alpha=0.65,
                           ax=ax,
                           **dzcnapy.small_attrs)
    nx.draw_networkx_nodes(ergraph, pos, ax=ax, **dzcnapy.small_attrs)
    dzcnapy.set_extent(pos, ax, "Threshold={}".format(threshold))

dzcnapy.plot("slicing")
コード例 #20
0
    return top_label_path.split(":")[-1]


mapping = {
    comm_id: "{}/{}".format(top_cat_label(subgraph), comm_id)
    for comm_id, subgraph in enumerate(subgraphs)
}
induced = nx.relabel_nodes(induced, mapping, copy=True)

attrs = {
    "edge_color": "gray",
    "font_size": 12,
    "font_weight": "bold",
    "node_size": 700,
    "node_color": "pink",
    "width": 2,
    "font_family": "Liberation Sans Narrow"
}

# Calculate best node positions
pos = graphviz_layout(induced)

# Draw the network
nx.draw_networkx(induced, pos, **dzcnapy.attrs)

# Adjust the extents
dzcnapy.set_extent(pos, plt)

# Save and show
dzcnapy.plot("ProductNetwork")
コード例 #21
0
}

sim_data = [pd.DataFrame([[func(att_mtx[e1], att_mtx[e2])
                               for e1 in att_mtx] for e2 in att_mtx],
                             columns=att_mtx.columns,
                             index=att_mtx.columns)
                for func in sim_funcs.values()]

def simm2net(simm):
    stacked = simm.stack()
    sliced = stacked[stacked >= 0.7]
    net = nx.from_pandas_dataframe(sliced.reset_index(),
                                   "level_0", "level_1")
    net.add_nodes_from(att_mtx.columns)
    return net

networks = map(simm2net, sim_data)

pos = None
for i, (g, name) \
        in enumerate(zip(networks, sim_funcs.keys())):
    ax = plt.subplot(2, 2, i + 1)
    if pos is None:
        pos = graphviz_layout(g)
    nx.draw_networkx_edges(g, pos, ax=ax, **dzcnapy.thick_attrs)
    nx.draw_networkx_nodes(g, pos, ax=ax, **dzcnapy.attrs)
    nx.draw_networkx_labels(g, pos, ax=ax, **dzcnapy.attrs)
    dzcnapy.set_extent(pos, ax, name)

dzcnapy.plot("event_networks")
コード例 #22
0
migrations = pd.read_csv("migration_2015.csv",
                         thousands=",").set_index("Unnamed: 0")

table_migrations = migrations.stack().reset_index()\
                                     .sort_values(0, ascending=False)\
                                     .groupby("Unnamed: 0").head(3)

table_migrations.columns = "From", "To", "weight"

G = nx.from_pandas_dataframe(table_migrations, "From", "To", 
                             edge_attr=["weight"],
                             create_using=nx.DiGraph())
nx.relabel_nodes(G, pd.read_csv("states.csv", header=None)\
                 .set_index(0)[2].to_dict(), copy=False)

print(sorted(nx.weakly_connected_components(G), key=len, reverse=True))
print(sorted(nx.strongly_connected_components(G), key=len, reverse=True))
attracting = sorted(nx.attracting_components(G), key=len, reverse=True)[0]
print(attracting)

pos = graphviz_layout(G)
dzcnapy.attrs["node_color"] = ["palegreen" if n in attracting 
                               else "pink" for n in G]

nx.draw_networkx_edges(G, pos, alpha=0.5, **dzcnapy.attrs)
nx.draw_networkx_nodes(G, pos, **dzcnapy.attrs)
nx.draw_networkx_labels(G, pos, **dzcnapy.attrs)

dzcnapy.set_extent(pos, plt)
dzcnapy.plot("migration", True)
コード例 #23
0
G2 = nx.balanced_tree(2, 5)
G3 = nx.grid_2d_graph(5, 4)
names = ("Linear (path)", "Ring (Cycle)", "Balanced Tree", "Mesh (Grid)",
         "Star", "Complete")

graphs = G0, G1, G2, G3, G4, G5
layouts = (graphviz_layout, ) * len(graphs)

for i, (g, name, layout) in enumerate(zip(graphs, names, layouts)):
    ax = plt.subplot(3, 2, i + 1)
    pos = layout(g)
    nx.draw_networkx_edges(g, pos, alpha=0.5, ax=ax, **dzcnapy.small_attrs)
    nx.draw_networkx_nodes(g, pos, ax=ax, **dzcnapy.small_attrs)
    dzcnapy.set_extent(pos, ax, name)

dzcnapy.plot("synthetic3")

#Generate and draw random networks
G0 = nx.erdors_renyi_graph(50, 0.05)
G1 = nx.connected_watts_strogatz_graph(50, 4, 0.05)
G2 = nx.barabasi_albert_graph(50, 4)
G3 = nx.powerlaw_cluster_graph(50, 4, 0.05)

names = ("Erdos-Renvi (p=0.05)", "Watts-Strogatz (k=4, p=0.5)",
         "Barabasi-Albert (k=4)", "Holme-Kim (k=4, p=0.5)")
graphs = G0, G1, G2, G3
layouts = (nx.circular_layout, nx.circular_layout, graphviz_layout,
           graphviz_layout)

for i, (g, name, layout) in enumerate(zip(graphs, names, layouts)):
    ax = plt.subplot(2, 2, i + 1)
コード例 #24
0
ranks = pd.read_csv("Adjectives_by_the_rank.csv",
                    header=1).set_index("ResponseID").fillna(0)
Q1 = "Rank the words from the most positive to the most negative-"
ranks = ranks.loc[:, ranks.columns.str.startswith(Q1)].astype(int)
ranks.columns = ranks.columns.str.replace(Q1, "")

dominance = pd.DataFrame([[(ranks[j] > ranks[i]).sum()
                           for i in ranks] for j in ranks],
                         columns=ranks.columns, index=ranks.columns)

QUORUM = 115
edges = sorted(dominance[dominance >= QUORUM].stack().index.tolist())
G = nx.DiGraph(edges)

# Sort in the reverse order
print(nx.topological_sort(G)[::-1])

edge_dict = {n1: set(ns) for n1, ns in nx.to_dict_of_lists(G).items()}
topo_order = list(toposort.toposort(edge_dict))
print(topo_order)

pos = graphviz_layout(G)
nx.draw_networkx_edges(G, pos, alpha=0.5, **dzcnapy.attrs)
nx.draw_networkx_nodes(G, pos, **dzcnapy.attrs)
nx.draw_networkx_labels(G, pos, **dzcnapy.attrs)

dzcnapy.set_extent(pos, plt)
dzcnapy.plot("adjectives")