Exemplo n.º 1
0
def plot_all_graphs(map_graph, start_year, end_year, folder):
    for year in range(start_year, end_year):
        plt.title("Graph" + str(year), fontsize=15)
        nx.draw_random(map_graph[str(year)], with_labels=False, node_size=100, node_color=[(0.73, 0.09, 0.19)],
                       node_cmap=cm.get_cmap("viridis"), edge_cmap=cm.get_cmap("binary"))
        plt.savefig(folder + "Graph" + str(year) + ".png", format="PNG")
        plt.show()
Exemplo n.º 2
0
def draw_graph(graph, showLabels = True):

    # extract nodes from graph
    nodes = set([n1 for n1, n2 in graph] + [n2 for n1, n2 in graph])

    # create network graph
    G=nx.Graph()

    # add nodes
    for node in nodes:
        G.add_node(node)

    # add edges
    for edge in graph:
        G.add_edge(edge[0], edge[1])

    # draw graph 1 in shell layout
    pos = nx.shell_layout(G)
    nx.draw(G, pos)
    plt.figure()

    # draw graph 2 with a random layout
    # might need to zoom in to see edges
    # labels are now on top of the nodes
    nx.draw_random(G)
    plt.figure()
    nx.draw_spring(G, node_size=100, with_labels=showLabels, font_size=16, edge_color="grey", width=0.5)

    # draw graph 3 the standard way and save
    plt.savefig("fig1.png")
    plt.show()
Exemplo n.º 3
0
	def nx_topoPrint(self):
		if self.nx_topology is None:
			print []
		else:
			print self.nx_topology.edges(data=True)
			nx.draw_random(self.nx_topology)
			plt.show()
def inventors_network(df, top_pairs=100):
    # converting from pandas Series to list after dropping Empty/Null values
    inventors = df["Inventors"].dropna().tolist()

    # making dictionary for assignee (key) -> # of patents (value)
    inventors_net = {}
    for j in inventors:
        inventor = j.split(";;")
        for i in inventor:
            for j in inventor:
                if i != j:
                    key1 = i + ',' + j
                    key2 = j + ',' + i
                    if key1 not in inventors_net.keys(
                    ) and key2 not in inventors_net.keys():
                        inventors_net[key1] = 1
                    elif key1 in inventors_net.keys():
                        inventors_net[key1] += 1
                    elif key2 in inventors_net.keys():
                        inventors_net[key2] += 1

    # sorted dictionary from high number of patents to low
    inventors_net_sorted = {
        k: v
        for k, v in sorted(
            inventors_net.items(), key=lambda item: item[1], reverse=True)
    }

    # parameter to get top n invetors plot
    out_net_inventor = dict(
        itertools.islice(inventors_net_sorted.items(), top_pairs))

    inventor1 = []
    inventor2 = []
    count = []
    for i in out_net_inventor:
        inven = i.split(',')
        inventor1.append(inven[0])
        inventor2.append(inven[1])
        count.append(out_net_inventor[i])

    df_net = pd.DataFrame({
        'inventor1': inventor1,
        'inventor2': inventor2,
        'patent_count': count
    })

    print('Inventors Network')

    G = nx.Graph()
    G = nx.from_pandas_edgelist(df_net,
                                'inventor1',
                                'inventor2',
                                edge_attr='patent_count')
    #count = [i['patent_count'] for i in dict(G.edges).values()]
    #labels = [i for i in dict(G.nodes).keys()]
    #labels = {i:i for i in dict(G.nodes).keys()}
    plt.figure(figsize=(15, 15))
    nx.draw_random(G, with_labels=True)
    plt.show()
 def draw_random_communities(self):
     partition = self.find_partition()[1]
     node_color=[float(partition[v]) for v in partition]
     labels = self.compute_labels()
     nx.draw_random(self.G,node_color=node_color, labels=labels)
     plt.show()
     plt.savefig("C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_random.pdf")
Exemplo n.º 6
0
def __main__():

    actors, movies = extract_from_json(
        'data.json', NUM_MOVIES, NUM_ACTORS)  # Get the ACTORS and MOVIES dict
    actors, movies = make_graph(actors,
                                movies)  # Draw the edges between these nodes
    # movies = get_movies_of_actors(actors)
    graph = nx.Graph()
    create_graph(
        graph, actors, movies
    )  # Add the nodes draw the edges between nodes in the networkx graph
    node_colors, node_sizes = get_node_attrs(
        graph)  # Get the node colors and sizes

    # Plot the graph
    plt.figure(figsize=FIG_SIZE)
    nx.draw_random(graph,
                   node_color=node_colors,
                   node_size=node_sizes,
                   with_labels=True)
    plt.savefig('actor_movie_graph_random.png')

    plt.figure(figsize=FIG_SIZE)
    nx.draw(graph,
            node_color=node_colors,
            node_size=node_sizes,
            with_labels=True)
    plt.savefig('actor_movie_graph.png')
def generator_by_json(d):
    G = nx.MultiDiGraph()
    for link, links in d.items():
        for link__ in links:
            for link1, links1 in link__.items():
                G.add_edge(link, link1)
                for link2__ in links1:
                    for link3, links3 in link2__.items():
                        G.add_edge(link1, link3)
                        for link___ in links3:
                            G.add_edge(link3, link___)

    plt.figure(figsize=(30, 30))
    options = {
        'node_color': 'red',
        'node_size': 12,
        'edge_color': 'blue',
        'width': 0.07
    }
    print('q')

    nx.write_gml(G, 'remote.gml')

    nx.draw_random(G, with_labels=False, **options)
    plt.savefig('foo.png')
    def custom_edge_colors():
        #create an empty graph
        G = nx.Graph()



        H=nx.path_graph(len(rez3))
        G.add_nodes_from(H),



        custom_node_color={}
        custom_node_color["H"] = "g"





        nx.draw_random(G, node_color=custom_node_color.values(), with_labels=False, node_size=5)


        C = nx.Graph()
        C.add_node("genom")
        custom_node_color={}
        custom_node_color["genom"] = "g"
        nx.draw_random(C, node_color=custom_node_color.values(), with_labels=True, node_size=2500)


        plt.show()
Exemplo n.º 9
0
def load(file_name):
    G = nx.MultiDiGraph()
    d: dict = json.load(open(file_name))
    for link, links in d.items():
        for link__ in links:
            link__: dict
            for link1, links1 in link__.items():
                link1: str
                G.add_edge(link, link1)
                for link2__ in links1:
                    for link3, links3 in link2__.items():
                        G.add_edge(link1, link3)
                        for link___ in links3:
                            G.add_edge(link3, link___)

    plt.figure(figsize=(40, 40))
    # nx.draw_networkx(G, node_color='green')
    options = {
        'node_color': 'red',
        'node_size': 10,
        'edge_color': 'blue',
        'width': 0.08
    }
    nx.write_gml(G, 'remote.gml')

    nx.draw_random(G, with_labels=False, **options)
    # plt.show()
    plt.savefig('foo.png')
Exemplo n.º 10
0
    def show_graph(self,
                   graph=None,
                   save_file=None,
                   drawing_type='internal',
                   pltshow=True):
        import matplotlib.pyplot as plt

        if graph is None:
            shown_graph = self._connected_subgraph
        else:
            shown_graph = graph

        plt.figure()
        # pos = nx.spring_layout(shown_graph)
        if drawing_type == 'internal':
            pos = nx.shell_layout(shown_graph)
            ax = plt.gca()
            draw_network(shown_graph,
                         pos,
                         ax,
                         periodicity_vectors=self._periodicity_vectors)
            ax.autoscale()
            plt.axis('equal')
            plt.axis('off')
            if save_file is not None:
                plt.savefig(save_file)
            # nx.draw(self._connected_subgraph)
        elif drawing_type == 'draw_graphviz':
            import networkx
            networkx.nx_pydot.graphviz_layout(shown_graph)
        elif drawing_type == 'draw_random':
            import networkx
            networkx.draw_random(shown_graph)
        if pltshow:
            plt.show()
Exemplo n.º 11
0
def countInformedNode3(G,t,info_source,info_other,N):
    states= nx.get_node_attributes(G,'state')
    count = 0
    color_map=[]
    if(N<500):
        for x in states:
            if(states[x]==info_source):
                count=count+1
                #informed
                color_map.append("red")
            elif(states[x]==(info_source+1%2)):
                #bad information
                color_map.append("blue")
            else:
                #uninformed
                color_map.append("green")
        plt.figure(t)
        nx.draw_random(G,node_color = color_map,with_labels=True)
        plt.savefig('static/foo'+str(t)+'.png')

    if(count==N):
        #print("all nodes are informed after "+str(t)+" rounds")
        return True
   # print("At the end of round  "+str(t)+" there are "+str(count)+" informed node")
    return False
Exemplo n.º 12
0
def draw_network(G: Graph,
                 output_name: str,
                 type_of_network: str = None) -> None:
    """
    Creates a drawing of the network, according to the selected type of network.

    Args:
        G (graph): the input graph
        output_name (string): the output name
        type_of_network (string): the type of network

    Returns:
        None. Just prints the image to a file into the folder data/
    """
    if type_of_network == "planar":
        nx.draw_planar(G, with_labels=True)
    elif type_of_network == "circular":
        nx.draw_circular(G, with_labels=True)
    elif type_of_network == "random":
        nx.draw_random(G, with_labels=True)
    elif type_of_network == "spectral":
        nx.draw_random(G, with_labels=True)
    elif type_of_network == "kamada_kawai":
        nx.draw_kamada_kawai(G, with_labels=True)
    elif type_of_network == "spring":
        nx.draw_spring(G, with_labels=True)
    elif type_of_network == "shell":
        nx.draw_shell(G, with_labels=True)
    else:
        nx.draw(G, with_labels=True)
    plt.savefig("images/" + output_name + "network_" + str(type_of_network) +
                ".png")
    plt.close()
Exemplo n.º 13
0
def draw_graph(g, out_filename):
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)

    plt.savefig(out_filename)
Exemplo n.º 14
0
	def nx_topoPrint(self):
		if self.nx_topology is None:
			print []
		else:
			print self.nx_topology.edges(data=True)
			nx.draw_random(self.nx_topology)
			plt.show()
Exemplo n.º 15
0
def draw_graph(g, out_filename):
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)

    plt.savefig(out_filename)
Exemplo n.º 16
0
    def draw_graph(self, G, node_list=None, edge_colour='k', node_size=15, node_colour='r', graph_type='spring',
                   back_bone=None, side_chains=None, terminators=None):
        # determine nodelist
        if node_list is None:
            node_list = G.nodes()
        # determine labels
        labels = {}
        for l_atom in G.nodes_iter():
            labels[l_atom] = l_atom.symbol

        # draw graphs based on graph_type
        if graph_type == 'circular':
            nx.draw_circular(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'random':
            nx.draw_random(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spectral':
            nx.draw_spectral(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'spring':
            nx.draw_spring(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                           edge_color=edge_colour, node_color=node_colour)
        elif graph_type == 'shell':
            nx.draw_shell(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                          edge_color=edge_colour, node_color=node_colour)
        # elif graph_type == 'protein':
        # self.draw_protein(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
        #                   edge_color=edge_colour, node_color=node_colour, back_bone, side_chains, terminators)
        else:
            nx.draw_networkx(G, with_labels=True, labels=labels, node_list=node_list, node_size=node_size,
                             edge_color=edge_colour, node_color=node_colour)
        plt.show()
Exemplo n.º 17
0
def draw_networkx_ex():
    G = nx.dodecahedral_graph()
    nx.draw(G)
    plt.show()
    nx.draw_networkx(G, pos=nx.spring_layout(G))
    limits = plt.axis('off')
    plt.show()
    nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
    plt.show()
    edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    plt.show()
    labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
    plt.show()
    edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
    plt.show()
    print("Circular layout")
    nx.draw_circular(G)
    plt.show()
    print("Random layout")
    nx.draw_random(G)
    plt.show()
    print("Spectral layout")
    nx.draw_spectral(G)
    plt.show()
    print("Spring layout")
    nx.draw_spring(G)
    plt.show()
    print("Shell layout")
    nx.draw_shell(G)
    plt.show()
    print("Graphviz")
Exemplo n.º 18
0
def draw():
    pos = nx.spring_layout(H)
    nx.draw_networkx_nodes(H, pos=pos, nodelist=H.nodes())
    nx.draw_networkx_edges(H, pos=pos, edgelist=H.edges())
    nx.draw_networkx_labels(H, pos=pos)
    nx.draw_random(H)
    plt.show()
Exemplo n.º 19
0
def start_graph(Nomserie, type_graph):
    print(type_graph)
    options = {
        'node_color': 'red',
        'node_size': 200,
        'width': 3,
    }

    if Nomserie == "Game of Thrones":
        G1 = nx.read_graphml("data/got/GoT_S05E09_1039.graphml")
        print(G1)
    if Nomserie == "Breaking Bad":
        G1 = nx.read_graphml("data/bb/BB_S03E11_598.graphml")
    if Nomserie == "House of Card":
        G1 = nx.read_graphml("data/hoc/HoC_S02E13_879.graphml")

    G1.remove_nodes_from(nx.isolates(G1))
    if type_graph == "Classical":
        nx.draw_networkx(G1, pos=nx.spring_layout(G1))
    if type_graph == "Random":
        nx.draw_random(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Circular":
        nx.draw_circular(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Spectral":
        nx.draw_spectral(G1, **options, with_labels=True, font_weight='bold')
    if type_graph == "Shell":
        nx.draw_shell(G1, **options, with_labels=True, font_weight='bold')
    plt.savefig("images/" + Nomserie + "_" + type_graph + ".jpg")
    plt.close('all')
Exemplo n.º 20
0
def draw_networkx_ex():
    G = nx.dodecahedral_graph()
    nx.draw(G)
    plt.show()
    nx.draw_networkx(G, pos=nx.spring_layout(G))
    limits = plt.axis('off')
    plt.show()
    nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
    plt.show()
    edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    plt.show()
    labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
    plt.show()
    edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
    plt.show()
    print("Circular layout")
    nx.draw_circular(G)
    plt.show()
    print("Random layout")
    nx.draw_random(G)
    plt.show()
    print("Spectral layout")
    nx.draw_spectral(G)
    plt.show()
    print("Spring layout")
    nx.draw_spring(G)
    plt.show()
    print("Shell layout")
    nx.draw_shell(G)
    plt.show()
    print("Graphviz")
Exemplo n.º 21
0
 def draw_random_communities(self):
     partition = self.find_partition()[1]
     node_color = [float(partition[v]) for v in partition]
     labels = self.compute_labels()
     nx.draw_random(self.G, node_color=node_color, labels=labels)
     plt.show()
     plt.savefig(
         "C:\\Users\\Heschoon\\Dropbox\\ULB\\Current trends of artificial intelligence\\Trends_project\\graphs\\graph_random.pdf"
     )
Exemplo n.º 22
0
def sample1():
    # 一定要建立一個物件,這物件就是包含所有的node跟edge
    G = nx.random_graphs.barabasi_albert_graph(100, 1)
    # nx.draw(G)
    nx.draw_random(G)
    # nx.draw_circular(G)
    # nx.draw_spectral(G)
    plt.savefig("test.png")
    plt.show()
Exemplo n.º 23
0
 def drawgraph(self, G):
     nx.draw(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph.png")
     nx.draw_random(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph_random.png")
     nx.draw_circular(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph_circular.png")
     nx.draw_spectral(G)
     plt.savefig(self.opts.o[0] + ".cluster_graph_spectral.png")
Exemplo n.º 24
0
 def drawplot(self, index):
     if index == 0:
         nx.draw_networkx(self.G, with_labels=False)
     elif index == 1:
         nx.draw_shell(self.G)
     elif index == 2:
         nx.draw_kamada_kawai(self.G, node_size=5, linewidths=0.5)
     elif index == 3:
         nx.draw_random(self.G)
Exemplo n.º 25
0
def main(argv):
    if len(argv) != 1:
        print "usage: python compare-food.py <path/to/allr_recipes.txt>"
        sys.exit(0)

    file_path = argv[0]

    # Change the criteria for the graphs here.
    mix_criteria = ['Canada', 'Scandinavia']

    recipes_list = []
    count = 0

    with open(file_path, 'r') as f:
        for line in f:
            split_line = line.split()
            country = split_line[0]

            if country in mix_criteria:
                ingredients = split_line[1:]
                recipes_list.append(ingredients)
                count += 1

    g_nx = nx.Graph()

    for recipe in recipes_list:
        edges = itertools.combinations(recipe, 2)
        g_nx.add_edges_from(edges)

    degrees = nx.degree(g_nx)

    # filtered_nodes = [n for n in degrees if degrees[n] < 50]
    # filtered_nodes = [n for n in degrees if 50 <= degrees[n] <= 100]
    filtered_nodes = [n for n in degrees if degrees[n] > 100]

    sub_graph = g_nx.subgraph(filtered_nodes)

    ds = nx.degree(sub_graph)

    plt.figure(figsize=(14, 14))

    nx.draw_random(sub_graph,
                   with_labels=True,
                   nodelist=ds.keys(),
                   node_size=[d * 70 for d in ds.values()],
                   font_size=8,
                   edge_color='grey')
    # nx.draw_random(g_nx, with_labels=True,
    #                nodelist=degrees.keys(), node_size=[d * 10 for d in degrees.values()],
    #                font_size=8, edge_color='grey')

    # plt.show()

    output_file = "-".join(mix_criteria) + ".elist.txt"
    plt.savefig(output_file + "-subgraph.png")

    print "Edge list is in: {}".format(output_file)
Exemplo n.º 26
0
def main():
    print("Graphing!")
    G = nx.Graph()
    G.add_nodes_from([1-3])
    G.add_edge(1, 2)

    nx.draw_random(G)
    nx.draw_circular(G)
    nx.draw_spectral(G)
    plt.show()
Exemplo n.º 27
0
def main():
    print("Graphing!")
    G = nx.Graph()
    G.add_nodes_from([1 - 3])
    G.add_edge(1, 2)

    nx.draw_random(G)
    nx.draw_circular(G)
    nx.draw_spectral(G)
    plt.show()
Exemplo n.º 28
0
def demo_save_fig():
    """demo_save_fig"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    plt.savefig("g.png")
Exemplo n.º 29
0
def demo_save_fig():
    """demo_save_fig"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    plt.savefig("g.png")
Exemplo n.º 30
0
    def draw(self):
        # nx.draw_planar(self.G, with_labels=True, font_weight='bold')
        # nx.draw_circular(self.G, with_labels=True, font_weight='bold')
        # nx.draw_kamada_kawai(self.G, with_labels=True, font_weight='bold')
        # nx.draw_spectral(self.G, with_labels=True, font_weight='bold')
        nx.draw_random(self.G, with_labels=True, font_weight='bold')
        # nx.draw_spring(self.G, with_labels=True, font_weight='bold')
        # nx.draw_shell(self.G, with_labels=True, font_weight='bold')

        plt.show()
Exemplo n.º 31
0
def draw_network(G, name, path, save, circular):

    if circular: nx.draw_circular(G)
    else: nx.draw_random(G)

    plt.axis('off')
    plt.title(name, fontweight='bold', fontsize=12)

    if save: plt.savefig(path + '_graph.pdf', bbox_inches='tight')
    plt.close()
Exemplo n.º 32
0
def showWGraph(n, W):
    geneGraph = nx.DiGraph()

    for i in range(n):
        for j in range(n):
            if (W[i, j] != 0):
                geneGraph.add_edge(j, i)

    nx.draw_random(geneGraph, with_labels=True)
    plt.show()
Exemplo n.º 33
0
def demo_write_doc():
    """demo_write_doc"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    nx.draw_graphviz(g)
    nx.write_dot(g, 'g.dot')
Exemplo n.º 34
0
 def test_draw(self):
     #         hold(False)
     N = self.G
     nx.draw_spring(N)
     pylab.savefig("test.png")
     nx.draw_random(N)
     pylab.savefig("test.ps")
     nx.draw_circular(N)
     pylab.savefig("test.png")
     nx.draw_spectral(N)
     pylab.savefig("test.png")
Exemplo n.º 35
0
def draw_graph(G, file):
    _deg = nx.degree(G)
    deg = [(_deg[node] + 1) for node in G.nodes()]

    nx.draw_random(G, node_size=deg, width=0.1, arrows=False)
    print(f"Save snapshot to {graph_dir}{file[:-5]}.eps")
    plt.savefig(f"{graph_dir}{file[:-5]}.eps")

    for edge in G.edges(data=True):
        print(edge)
        break
Exemplo n.º 36
0
    def test_draw(self):
#         hold(False)
        N=self.G
        nx.draw_spring(N)
        pylab.savefig("test.png")
        nx.draw_random(N)
        pylab.savefig("test.ps")
        nx.draw_circular(N)
        pylab.savefig("test.png")
        nx.draw_spectral(N)
        pylab.savefig("test.png")
Exemplo n.º 37
0
def demo_write_doc():
    """demo_write_doc"""
    g = nx.Graph()
    g.add_edges_from([(1, 2), (1, 3)])
    g.add_node('sparm')
    nx.draw(g)
    nx.draw_random(g)
    nx.draw_circular(g)
    nx.draw_spectral(g)
    nx.draw_graphviz(g)
    nx.write_dot(g, 'g.dot')
Exemplo n.º 38
0
 def draw_curr(self, pos=None):
     '''
     Draw discovered graph
     '''
     plt.figure(1, figsize=(30, 30))
     plt.clf()
     self.sub = nx.subgraph(self.graph, self.active.union(self.possible_actions))
     if pos is None:
         nx.draw_random(self.sub, with_labels=True)
     else:
         nx.draw(self.sub, with_labels=True, pos=pos)
Exemplo n.º 39
0
    def show(self, mode=None):

        if not mode:
            nx.draw(self)
        elif mode == 'random':
            nx.draw_random(self)
        elif mode == 'circular':
            nx.draw_circular(self)
        elif mode == 'spectral':
            nx.draw_spectral(self)

        plt.show()
Exemplo n.º 40
0
	def visualize(self):
		g = None
		if self.directed:
			g = nx.DiGraph()
		else:
			g = nx.Graph()


		g.add_edges_from(self.edges())

		nx.draw_random(g)
		plt.show()
Exemplo n.º 41
0
def nx_plot(r_graph,
            cols_names,
            simple=True,
            labels=None,
            graph_layout='shell',
            node_size=1600,
            node_color='blue',
            node_alpha=0.3,
            node_text_size=12,
            edge_color='blue',
            edge_alpha=0.3,
            edge_tickness=1,
            edge_text_pos=0.3,
            text_font='sans-serif'):

    #G = nx.Graph()
    dg = nx.DiGraph()
    edges = []
    np_amat = np.asarray(bnlearn.amat(r_graph))
    for ri in range(np_amat.shape[0]):
        for ci in range(np_amat.shape[1]):
            if np_amat[ri, ci] == 1:
                #G.add_edge(cols_names[ri],cols_names[ci])
                dg.add_edge(cols_names[ri], cols_names[ci])
                edges.append((cols_names[ri], cols_names[ci]))

    #import pdb;pdb.set_trace()
    if simple:
        if graph_layout == 'spectral':
            nx.draw_spectral(dg, font_size=node_text_size)
        elif graph_layout == 'random':
            nx.draw_random(dg, font_size=node_text_size)
        elif graph_layout == 'circular':
            nx.draw_circular(dg, font_size=node_text_size)
        elif graph_layout == 'spring':
            nx.draw_spring(dg, font_size=node_text_size)
        else:
            nx.draw(dg, font_size=node_text_size)
    else:
        draw_graph(edges,
                   directed=True,
                   labels=labels,
                   graph_layout=graph_layout,
                   node_size=node_size,
                   node_color=node_color,
                   node_alpha=node_alpha,
                   node_text_size=node_text_size,
                   edge_color=edge_color,
                   edge_alpha=edge_alpha,
                   edge_tickness=edge_tickness,
                   edge_text_pos=edge_text_pos,
                   text_font=text_font)
Exemplo n.º 42
0
 def test_draw(self):
     N=self.G
     nx.draw_spring(N)
     plt.savefig("test.ps")
     nx.draw_random(N)
     plt.savefig("test.ps")
     nx.draw_circular(N)
     plt.savefig("test.ps")
     nx.draw_spectral(N)
     plt.savefig("test.ps")
     nx.draw_spring(N.to_directed())
     plt.savefig("test.ps")
     os.unlink('test.ps')
Exemplo n.º 43
0
def main():
    graph = FBGraph(auth)
    data = graph.get_friends()
    for line in data:
        print line
    friends = graph.make_friends(data)
    graph.add_friend_nodes(friends)
    graph.add_likes(friends)
    friend_graph = graph.get_friend_graph()
    print '\n'
    print nx.clustering(friend_graph)
    print '\n'
    for edge in sorted(friend_graph.edges(data=True), key= lambda x: -1*x[2].get('weight', 1)):
        print edge
    nx.draw_random(friend_graph)
 def crearRed(self):
     mensajes = self.moduloPersistencia.getReplicasSeguimiento(self.identificador)
     nodos = set()
     relaciones = set()
     for k in mensajes:
         nodos.add(k["id_str"])
         nodos.add(k["in_reply_to_status_id"])
         relaciones.add((k["id_str"], k["in_reply_to_status_id"]))
     print(nodos)
     print(relaciones)
     grafo = nx.Graph()
     grafo.add_nodes_from(nodos)
     grafo.add_edges_from(relaciones)
     print(nx.info(grafo))
     nx.draw_random(grafo)
     plt.savefig("red.png")
Exemplo n.º 45
0
 def test_draw(self):
     try:
         N = self.G
         nx.draw_spring(N)
         plt.savefig('test.ps')
         nx.draw_random(N)
         plt.savefig('test.ps')
         nx.draw_circular(N)
         plt.savefig('test.ps')
         nx.draw_spectral(N)
         plt.savefig('test.ps')
         nx.draw_spring(N.to_directed())
         plt.savefig('test.ps')
     finally:
         try:
             os.unlink('test.ps')
         except OSError:
             pass
Exemplo n.º 46
0
def print_undirected_graph_nx(vertices, edges, name, draw_spring=False):
  G=nx.Graph()

  for v in vertices:
    G.add_node(v)

  for v in vertices:
    for e in edges:
      G.add_edge(e[0], e[1])

  if not draw_spring:
    nx.draw(G, with_labels=True, node_color='y')
  else:
    nx.draw_random(G, with_labels=True, node_color='y')
  #nx.draw_networkx_edge_labels(G,labels)
  plt.savefig("%s.png" % name) # save as png
  #plt.show()
  plt.clf()
Exemplo n.º 47
0
def draw_all(graph):
    """ Draw all different layout types for graph """
    nx.draw(graph)
    plt.savefig(path + 'draw.png')
    plt.close()
    nx.draw_circular(graph)
    plt.savefig(path + 'draw_circular.png')
    plt.close()
    nx.draw_random(graph)
    plt.savefig(path + 'draw_random.png')
    plt.close()
    nx.draw_spectral(graph)
    plt.savefig(path + 'draw_spectral.png')
    plt.close()
    nx.draw_spring(graph)
    plt.savefig(path + 'draw_spring.png')
    plt.close()
    nx.draw_shell(graph)
    plt.savefig(path + 'draw_shell.png')
    plt.close()
Exemplo n.º 48
0
def try_different_layouts(graph):
    layout_dir = 'graph_layout'
    if not os.path.exists(layout_dir):
        os.mkdir('graph_layout')
    nx.draw_random(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'rand.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_circular(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'circular.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_spectral(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'spectral.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_networkx(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'networkx.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw(graph, pos=graphviz_layout(graph), with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4,
            edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'graphviz.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_shell(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'shell.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()

    nx.draw_spring(graph, with_labels=True, font_size=16, node_size=500, alpha=0.8, width=4, edge_color='grey')
    plt.axis('off')
    plt.savefig(layout_dir + os.sep + 'spring.png', bbox_inches='tight', pad_inches=0, transparent=True)
    plt.show()
Exemplo n.º 49
0
def network_plot(H, random = True, save = False, diff_color = True):                 
    """
    Overview
    -----------------
    This is used to plot social network graphs
    
    Input
    -----------------
    H is assumed to be a networkx network graph    
    
    if random is False, display mechanism will use default networkx
    representation of graph
    
    save designates whether the plot should be saved to file
    
    diff_color designates whether the plot should include different colors
    of agents or not
    """    
    color_array = []
    label_dict = {}
    
    for node in H.nodes():
        color_array.append(node.get_color())
                    
        label_dict[node] = node.get_name()
        
    if random and diff_color:
        nx.draw_random(H, node_color = color_array, labels = label_dict)  
    elif random and not diff_color:
        nx.draw_random(H, labels = label_dict)
    elif not random and diff_color:
        nx.draw(H, node_color = color_array, labels = label_dict)
    elif not random and not diff_color:
        nx.draw(H, labels = label_dict)
        
    if save:
        mpl.pyplot.savefig("social_network_graph.png")
    mpl.pyplot.show()
Exemplo n.º 50
0
def nx_plot(r_graph, cols_names, simple=True, labels=None, graph_layout='shell',
               node_size=1600, node_color='blue', node_alpha=0.3,
               node_text_size=12,
               edge_color='blue', edge_alpha=0.3, edge_tickness=1,
               edge_text_pos=0.3,
               text_font='sans-serif'):
    
    #G = nx.Graph()
    dg = nx.DiGraph()
    edges = []
    np_amat = np.asarray(bnlearn.amat(r_graph))
    for ri in range(np_amat.shape[0]):
        for ci in range(np_amat.shape[1]):
            if np_amat[ri,ci] == 1:
                #G.add_edge(cols_names[ri],cols_names[ci])
                dg.add_edge(cols_names[ri],cols_names[ci])
                edges.append((cols_names[ri],cols_names[ci]))
                
    #import pdb;pdb.set_trace()
    if simple:            
        if graph_layout=='spectral':
            nx.draw_spectral(dg,font_size=node_text_size)
        elif graph_layout=='random':
            nx.draw_random(dg,font_size=node_text_size)  
        elif graph_layout=='circular':
            nx.draw_circular(dg,font_size=node_text_size)  
        elif graph_layout=='spring':
            nx.draw_spring(dg,font_size=node_text_size)  
        else:
            nx.draw(dg,font_size=node_text_size)
    else:
        draw_graph(edges,directed=True, labels=labels, graph_layout=graph_layout,
               node_size=node_size, node_color=node_color, node_alpha=node_alpha,
               node_text_size=node_text_size,
               edge_color=edge_color, edge_alpha=edge_alpha, edge_tickness=edge_tickness,
               edge_text_pos=edge_text_pos,
               text_font=text_font)
Exemplo n.º 51
0
def show_cluster_example(sim_threshold):
    g = graph.Graph(simm, 150)

    clustersize_clique = [c for c in g.cliques() if len(c) == 8][0]
    sg = g.nx_graph.subgraph(clustersize_clique)
    nx.draw_circular(sg, alpha=0.8, node_size=2000, node_color='b')
    plt.show()

    clustersize_star = [c for c in g.star() if len(c) == 10][0]
    sg = g.nx_graph.subgraph(clustersize_star)
    pos = nx.spring_layout(sg)
    nx.draw(sg, alpha=0.8, node_size=2000, node_color='b', pos=pos)
    plt.show()

    clustersize_string = g.string()[0]
    sg = g.nx_graph.subgraph(clustersize_string)
    nx.draw_random(sg, alpha=0.8, node_size=2000, node_color='b')
    plt.show()

    #g = graph.Graph(simm, 600)

    clustersize_single_link = []# map(len, g.single_link())

    return [sim_threshold, clustersize_clique, clustersize_single_link, clustersize_star, clustersize_string]
Exemplo n.º 52
0
gradoTre = grafoTre.degree().values()
numpy.savetxt("../data/DistrGrado_Tre", gradoTre, fmt="%d", newline="\n")
istoGradoTre = networkx.degree_histogram(grafoTre)
numpy.savetxt("../data/IstoGrado_Tre", istoGradoTre, fmt="%d", newline="\n")
treCell["grado"] = gradoTre
treCell.to_csv("../data/Tre_towers.csv")


# In[9]:

get_ipython().magic(u"matplotlib inline")

pyplot.figure(figsize=(16, 9))
pyplot.subplot(222)
networkx.draw_random(grafoTim)

pyplot.subplot(221)
networkx.draw_random(grafoVoda)

pyplot.subplot(223)
networkx.draw_random(grafoWind)

pyplot.subplot(224)
networkx.draw_random(grafoTre)

pyplot.show()


# In[60]:
Exemplo n.º 53
0
 def test_edge_colors_and_widths(self):
     nx.draw_random(self.G, edgelist=[(0, 1), (0, 2)], width=[1, 2], edge_colors=['r', 'b'])
Exemplo n.º 54
0
	if shared_domains[key] == 0:
		print key
	else:
		if perc_shared_domains[key] > 4.6:#(float(1)/1103)*100: # thresholding
			G.add_edge(key[0],key[1],weight=perc_shared_domains[key])#{'weight':perc_shared_domains[key]*100})
		
		#G.add_edge(key[0],key[1],weight=perc_shared_domains[key]) # complete network
vals = sorted([G[n[0]][n[1]]['weight'] for n in G.edges()])
#values = [int(10*(G[n[0]][n[1]]['weight'])) for n in G.edges()] # ?????
jet = cm = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=vals[0], vmax=vals[-1])
#cNorm = colors.Normalize(vals)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)


colorList = []
for i in range(len([int(G[n[0]][n[1]]['weight']) for n in G.edges()])):
      colorVal = scalarMap.to_rgba(vals[i])
      # print [G[n[0]][n[1]]['weight'] for n in G.edges()][i]
      # print colorVal
      colorList.append(colorVal)

deg_dist = []
for n in G.nodes():
	deg_dist.append(G.degree(n))
print deg_dist

#print colorList
nx.draw_random(G,edge_color=colorList,font_size="18",font_weight="bold",bbox="m")
plt.show()
Exemplo n.º 55
0
 def draw(self):
     nx.draw_random(self.graph)
     plt.show(block=False)
#            pass

print "REPLY COUNTS"
print userfreq            
print freq
print poi_retweet

print "Mention COUNTS"
#print mentions_count
#print usermentionsfreq
#print poi_mentions

G=nx.DiGraph()
#A=pgv.AGraph()

for edge in edges:
    G.add_edge(edge[0],edge[1])
    #A.add_edge(edge[0],edge[1])

#A.layout() # layout with default (neato)
#A.draw('simple.png') # draw png

#export so you can use gephi
nx.write_graphml(G,'ed-test-mentions-replies-to.graphml')
nx.write_gexf(G, 'ed-test-mentions-replies-to.gexf')

# nx.draw_spring(G)
# nx.draw_shell(G)
nx.draw_random(G)

plt.show()
Exemplo n.º 57
0
print("nxdraw")
nx.draw(graph, node_color=node_color, node_size=node_size)
print("plt save")
plt.savefig("path_full.png")

print("Printing cir picture")
plt.clf()
print("nxdraw")
nx.draw_circular(graph, node_color=node_color, node_size=node_size)
print("plt save")
plt.savefig("path_full_cir.png")

print("Printing rand picture")
plt.clf()
print("nxdraw")
nx.draw_random(graph, node_color=node_color, node_size=node_size)
print("plt save")
plt.savefig("path_full_rand.png")

"""print("Printing spectral picture")
plt.clf()
nx.draw_spectral(graph, node_color=node_color, node_size=node_size)
plt.savefig("path_full_spectral.png")

print("Printing spring picture")
plt.clf()
nx.draw_spring(graph, node_color=node_color, node_size=node_size)
plt.savefig("path_full_spring.png")

print("Printing shell picture")
plt.clf()
Exemplo n.º 58
0
def main():
    # 1.0 Loading a local data file
    # Load the Hartford drug users data, a directed binary graph.
    # We will specify that the graph be generated as a directed graph, and
    # that the nodes are integers (rather than strings)
    hartford=nx.read_edgelist("../../data/hartford_drug.txt",create_using=nx.DiGraph(),nodetype=int)
    nx.info(hartford)  # Check the the data has been loaded properly

    # 2.0 Connecting to a database

    # 3.0 Building a network directly from the Internet
    # WARNING: This can take a long time to run!
    seed="imichaeldotorg"   # Set the seed user within livejournal.com
    seed_url="http://"+seed+".livejournal.com"
    # 3.1 Scrape, parse and build seed's ego net
    sg=get_sg(seed_url)
    net,newnodes=create_egonet(sg)
    nx.write_pajek(net,"../../data/"+seed+"_ego.net") # Save data as Pajek
    nx.info(net)
    # 3.2 Perform snowball search, where k=2
    k=2
    for g in range(k):
        net,newnodes=snowball_round(net,newnodes)
        nx.write_pajek(net,"../../data/"+seed+"_step_"+str(g+1)+".net")
    
    # 4.0 Calculate in-degree centrality for Hartford data
    in_cent=nx.in_degree_centrality(hartford)
    
    # 5.0 Calculating multiple measures, and finding
    # most central actors
    hartford_ud=hartford.to_undirected()
    hartford_mc=nx.connected_component_subgraphs(hartford_ud)[0]    # First, extract MC
    # 5.1 Calculate multiple measures on MC
    bet_cen=nx.betweenness_centrality(hartford_mc)
    clo_cen=nx.closeness_centrality(hartford_mc)
    eig_cen=nx.eigenvector_centrality(hartford_mc)
    # 5.2 Find the actors with the highest centrality for each measure,
    print("Actor "+str(highest_centrality(bet_cen))+" has the highest Betweenness centrality")
    print("Actor "+str(highest_centrality(clo_cen))+" has the highest Closeness centrality")
    print("Actor "+str(highest_centrality(eig_cen))+" has the highest Eigenvector centrality")
    
    # 6.0 Calculating degree distribution
    ba_net=nx.barabasi_albert_graph(1000,2)   # Create a Barabasi-Albert network
    # 6.1 NX has a nice built-in function for degree distribution
    dh=nx.degree_histogram(ba_net)
    # 6.2 Plot using same method as http://networkx.lanl.gov/examples/drawing/degree_histogram.html
    pos=nx.spring_layout(ba_net)
    P.figure(figsize=(8,8))
    P.loglog(dh,'b-',marker='o')
    P.title("Degree rank plot (log-log)")
    P.ylabel("Degree")
    P.xlabel("Frequency")
    # 6.4 Draw graph in inset
    P.axes([0.45,0.45,0.45,0.45])
    P.axis('off')
    nx.draw_networkx_nodes(ba_net,pos,node_size=20)
    nx.draw_networkx_edges(ba_net,pos,alpha=0.4)
    P.savefig("../../images/figures/ba_10000.png")
    
    # 6.0 Finding community structure
    clus=nx.clustering(hartford_mc,with_labels=True)
    # 6.1 Get counts of nodes membership for each clustering coefficient
    unique_clus=list(unique(clus.values()))
    clus_counts=zip(map(lambda c: clus.values().count(c),unique_clus),unique_clus)
    clus_counts.sort()
    clus_counts.reverse()
    # 6.2 Create a subgraph from nodes with most frequent clustering coefficient
    mode_clus_sg=nx.subgraph(hartford_mc,[(a) for (a,b) in clus.items() if b==clus_counts[0][1]])
    P.figure(figsize=(6,6))
    nx.draw_spring(mode_clus_sg,with_labels=False,node_size=60,iterations=1000)
    P.savefig('../../images/networks/mode_clus_sg.png')
    
    # 7.0 Plot Eigenvector centrality vs. betweeness in matplotlib
    centrality_scatter(bet_cen,eig_cen,"../../images/figures/drug_scatter.png",ylab="Eigenvector Centrality",xlab="Betweenness Centrality",title="Hartford Drug Network Key Actor Analysis",reg=True)
    
    # 8.0 Outputting network data
    # First, output the data as an adjaceny list
    nx.write_adjlist(hartford_mc,"../../data/hartford_mc_adj.txt")
    # 8.1 Add metric data to the network object
    hartford_mc_met=add_metric(hartford_mc,eig_cen)
    print(hartford_mc_met.nodes(data=True)[1:10])   # Check the the data was stored
    # 8.2 output data using the Pajak format to save the node attribute data
    nx.write_pajek(hartford_mc,"../../data/hartford_mc_metric.net")    # NX will automatically add all attibute data to output
    
    # 9.0 Exporting data to a CSV file
    csv_data={"Betweeness":bet_cen,"Closeness":clo_cen,"Eigenvector":eig_cen}
    # 9.1 After we have all the data in a single dict, we send it to out function
    # to export the data as a CSV
    csv_exporter(csv_data,"../../data/drug_data.csv")
    
    # 10.0 Visualization basics
    # 10.1 Use subplots to draw random and circular layouts
    # of drug net side-by-side
    fig1=P.figure(figsize=(9,4))
    fig1.add_subplot(121)
    nx.draw_random(hartford_mc,with_labels=False,node_size=60)
    fig1.add_subplot(122)
    nx.draw_circular(hartford_mc,with_labels=False,node_size=60)
    P.savefig("../../images/networks/rand_circ.png")
    # 10.2 Draw spring, spectral layouts
    P.figure(figsize=(8,8))
    nx.draw_spring(hartford_mc,with_labels=False,node_size=60,iterations=10000)
    P.savefig("../../images/networks/spring.png")
    P.figure(figsize=(8,8))
    nx.draw_spectral(hartford_mc,with_labels=False,node_size=60,iterations=10)
    P.savefig("../../images/networks/spectral.png")
    # 10.3 Draw shell layout with inner-circle as the 25th percentile 
    # Eigenvector centrality actors
    P.figure(figsize=(8,8))
    # Find actors in 25th percentile
    max_eig=max([(b) for (a,b) in eig_cen.items()])
    s1=[(a) for (a,b) in eig_cen.items() if b>=.25*max_eig]
    s2=hartford_mc.nodes()
    # setdiff1d is a very useful NumPy function!
    s2=list(setdiff1d(s2,s1))       
    shells=[s1,s2]    
    # Calculate psotion and draw          
    shell_pos=nx.shell_layout(hartford_mc,shells)
    nx.draw_networkx(hartford_mc,shell_pos,with_labels=False,node_size=60)
    P.savefig("../../images/networks/shell.png")
    
    # 11.0 Adding analysis to visualization
    P.figure(figsize=(15,15))
    P.subplot(111,axisbg="lightgrey")
    spring_pos=nx.spring_layout(hartford_mc,iterations=1000)
    # 11.1 Use betweeneess centrality for node color intensity
    bet_color=bet_cen.items()
    bet_color.sort()
    bet_color=[(b) for (a,b) in bet_color]
    # 11.2 Use Eigenvector centrality to set node size
    eig_size=eig_cen.items()
    eig_size.sort()
    eig_size=[((b)*2000)+20 for (a,b) in eig_size]
    # 11.3 Use matplotlib's colormap for node intensity 
    nx.draw_networkx(hartford_mc,spring_pos,node_color=bet_color,cmap=P.cm.Greens,node_size=eig_size,with_labels=False)
    P.savefig("../../images/networks/analysis.png")
Exemplo n.º 59
0
# open the participants1 text file and read the file in line by line separated by tabs
with open("participantslist1.txt", "rU") as f:
    reader=csv.reader(f, delimiter="\t")
    d = list(reader)[1:] # store contents in a 2D array of rows and columns


fileindex=0
i=0
while fileindex < len(d):
    count=int(d[fileindex][0])
    for j in range (1, count+1):
        graph.add_node(d[fileindex+j][1])
    for j in range (1, count+1):
        for k in range (j, count+1):
            if j!=k:
                graph.add_edge(d[fileindex+j][1],d[fileindex+k][1])
                i=int(d[fileindex+j][0])
                graph[d[fileindex+j][1]][d[fileindex+k][1]]['project']=projects[i]
    fileindex=fileindex+count+1
print graph

nx.draw(graph, with_labels=False)
nx.draw_random(graph)
nx.draw_circular(graph)
nx.draw_spectral(graph)
plt.show()