コード例 #1
0
def main():
    edges = []   # 图的所有边信息
    domain_name = 'taobao.com'
    domain_pkts = get_data(domain_name)

    for i in domain_pkts[0]['details']:
        for v in i['answers']:
            edges.append((v['domain_name'],v['dm_data']))

    plt.figure(1, figsize=(10, 8))
    G = nx.Graph()
    G.add_edges_from(edges)

    pos = graphviz_layout(G, prog="fdp") #neato fdp
    C = nx.connected_component_subgraphs(G)  # 获取图的子图,用来标记颜色

    for g in C:
        c = [random.random()] * nx.number_of_nodes(g)
        nx.draw(g,
                pos,
                node_size=90,
                node_color=c,
                vmin=0.0,
                vmax=1.0,
                with_labels=False
        )
    plt.savefig('./graph/'+domain_name+"_relation.png", dpi=75)
    plt.show()
コード例 #2
0
def draw_relation_graph(G,node_ip,node_main,node_cname):
    from networkx.drawing.nx_pydot import graphviz_layout
    node_size =100
    pos = graphviz_layout(G, prog="fdp")  # neato fdp
    nx.draw_networkx_nodes(G, pos=pos, node_size=node_size, nodelist=node_ip, node_color='red', label="IP")
    nx.draw_networkx_nodes(G, pos=pos, node_size=node_size, nodelist=node_cname, node_color='green', label="CNAME")
    nx.draw_networkx_nodes(G, pos=pos, node_size=160, nodelist=node_main, node_color='blue', label="Main")
    nx.draw_networkx_edges(G, pos=pos)
    # nx.draw_networkx_labels(G, pos, font_size=10) # show the node labe
    plt.legend(loc='lower center', ncol=3, shadow=True, numpoints=1)
    plt.axis('off')
    plt.savefig('./graph/dd_type.png', dpi=75)
    plt.show()
コード例 #3
0
def main():
    """
    无图例展示
    :return:
    """
    edges = []   # 图的所有边信息
    domain_name = 'jd.com'
    domain_pkts = get_data(domain_name)
    from collections import defaultdict
    node_dict = defaultdict(set)
    for i in domain_pkts[0]['details']:
        for v in i['answers']:
            if v['dm_type'] == 'CNAME':
                node_dict[v['domain_name']].add('main')
                node_dict[v['dm_data']].add('cname')
            else:
                node_dict[v['dm_data']].add('ip')
                node_dict[v['domain_name']].add('main')
            edges.append((v['domain_name'],v['dm_data']))
    node_cat ={}
    for i in node_dict:
        if 'ip' in list(node_dict[i]):
            node_cat[i]='ip'
        elif 'cname' in list(node_dict[i]):
            node_cat[i]='cname'
        else:
            node_cat[i]='main'

    plt.figure(1,figsize=(10,8))
    G=nx.Graph()
    G.add_edges_from(edges)

    for node in G.nodes():
        G.node[node]['category'] = node_cat[node]

    color_map = {'main': 'b', 'cname': 'c', 'ip': 'r'}
    pos = graphviz_layout(G, prog="neato")  # neato fdp
    # pos = nx.random_layout(G)
    nx.draw(G,
            pos,
            node_size=100,
            node_color=[color_map[G.node[node]['category']] for node in G],
            label="nihao"
            )
    plt.axis('off')
    plt.savefig('./graph/' + domain_name + "_type.png", dpi=75)
    plt.show()
コード例 #4
0
def show(G: nx.DiGraph):

    scale = 1000

    pos = graphviz_layout(G, prog='dot')
    new_pos = nx.rescale_layout(pos=np.array(list(pos.values())), scale=scale).tolist()
    for idx,key in enumerate(pos.keys()):
        pos[key] = new_pos[idx]

    nx.set_edge_attributes(G, 'color', 'r')
    labels = nx.get_node_attributes(G, 'fancy_label')

    nx.draw_networkx(G, pos=pos, arrows=True, labels=labels, edge_color='r' )

    # plt.savefig(f"plot_{uuid.uuid4()}.png", dpi=1000)

    plt.show()
コード例 #5
0
def main1():
    """
    有图例,图例需要再进行更改
    :return:
    """
    edges = []
    node_main = []
    node_cname = []
    node_ip = []
    domain_name = 'jd.com'
    domain_pkts = get_data(domain_name)
    from collections import defaultdict
    node_dict = defaultdict(set)
    for i in domain_pkts[0]['details']:
        node_main.append(i['qry_name'])
        for v in i['answers']:
            if v['dm_type'] == 'CNAME':
                node_dict[v['domain_name']].add('main')
                node_dict[v['dm_data']].add('cname')
            else:
                node_dict[v['dm_data']].add('ip')
                node_dict[v['domain_name']].add('main')
            edges.append((v['domain_name'], v['dm_data']))

    for i in node_dict:

        if 'ip' in list(node_dict[i]):
            node_ip.append(i)
        elif 'cname' in list(node_dict[i]):
            node_cname.append(i)

    plt.figure(1, figsize=(8, 6))
    G = nx.Graph()
    G.add_edges_from(edges)
    node_size = 120
    pos = graphviz_layout(G, prog="neato")  # neato fdp
    nx.draw_networkx_nodes(G,pos=pos,node_size=node_size,nodelist=node_ip,node_color='red',label="IP")
    nx.draw_networkx_nodes(G, pos=pos,node_size=node_size, nodelist=node_cname, node_color='green', label="CNAME")
    nx.draw_networkx_nodes(G, pos=pos, node_size=160,nodelist=node_main, node_color='blue', label="Main")
    nx.draw_networkx_edges(G,pos=pos)
    plt.legend(loc='lower center',ncol=3, shadow=True,numpoints=1)
    plt.axis('off')
    plt.savefig('./graph/' + domain_name + "_type.png", dpi=75)
    plt.show()
コード例 #6
0
    def layout(self):
        """Initialize the CausalModel object by reading the information from the dot file with the passed path.

        The file should be a `dot` file and if it contains multiple graphs, only the first such graph is returned. All graphs _except_ the first are silently ignored.

        Parameters
        ----------
        path : str or file
            Filename or file handle.

        Returns
        -------
        None

        Examples
        --------
        >>> G = CausalModel()
        >>> G.load_model('temp.dot')

        Notes
        -----
        The heavy lifting is done by `networkx.drawing.nx_pydot.read_dot`

        """
        pos = graphviz_layout(self.dag, 'dot')

        keys = list(pos.keys())
        coords = np.array([pos[key] for key in keys])
        coords = nx.rescale_layout(coords, 1)
        pos = dict(zip(keys, coords))

        xs = []
        ys = []

        for key, value in pos.items():
            xs.append(value[0])
            ys.append(value[1])

        # All xx coordinates are the same, switch x and y
        # To make it horizontal instead of vertical
        if len(set(xs)) == 1:
            pos = {key: [-value[1], value[0]] for key, value in pos.items()}

        return pos
コード例 #7
0
def visualize_peer_client_network(G):
    # Draw client/ peer network using matplotlib
    fig = plt.figure(figsize=(10,10))
    master_nodes = [n for (n,ty) in \
        nx.get_node_attributes(G,'type').items() if ty == 'peer']
    client_nodes = [n for (n,ty) in \
        nx.get_node_attributes(G,'type').items() if ty == 'client']

    pos = graphviz_layout(G)

    nx.draw_networkx_nodes(G, pos, nodelist=master_nodes, \
        node_color='blue', node_shape='o', node_size=500)
    nx.draw_networkx_nodes(G, pos, nodelist=client_nodes,  \
        node_color='green', node_shape='^', node_size=100, label=1)

    nx.draw_networkx_labels(G, pos, labels={k:k for k in master_nodes}, font_color='w')

    nx.draw_networkx_edges(G, pos, edgelist=G.subgraph(master_nodes).edges(), width=1.5)
    nx.draw_networkx_edges(G, pos, edgelist=G.edges(nbunch=client_nodes),  style='dotted')
コード例 #8
0
def visualize_graph(g: nx.DiGraph) -> Plox:
    with Plox() as px:
        nodes_0 = ["___"]
        nodes_1 = [
            n for (n, k) in g.nodes(data='kind')
            if (k != "aa") and (n.count('_') == 2)
        ]
        nodes_2 = [
            n for (n, k) in g.nodes(data='kind')
            if (k != "aa") and (n.count('_') == 1)
        ]
        nodes_3 = [
            n for (n, k) in g.nodes(data='kind')
            if (k != "aa") and (n.count('_') == 0)
        ]
        nodes_aa = [n for (n, k) in g.nodes(data='kind') if (k == "aa")]

        pos = graphviz_layout(g, prog="twopi", root='___')
        # pos = nx.spring_layout(g, pos=pos)
        # pos = nx.shell_layout(g, nlist=[nodes_0, nodes_1, nodes_2, nodes_3, nodes_aa])
        # pos = nx.planar_layout(g)
        # pos = nx.kamada_kawai_layout(g)
        # pos = nx.spring_layout(g, pos=pos, k=10, iterations=10, threshold=1e-8)

        nx.draw_networkx_edges(g, pos=pos)

        nx.draw_networkx_nodes(g,
                               pos=pos,
                               nodelist=(nodes_0 + nodes_1 + nodes_2 +
                                         nodes_3))
        nx.draw_networkx_nodes(g, pos=pos, nodelist=nodes_aa, node_color='r')

        labels = {
            n: {
                'aa': n,
                'origin': "-",
                None: last(n.strip('_'), None)
            }[k]
            for (n, k) in g.nodes(data='kind')
        }
        nx.draw_networkx_labels(g, pos=pos, labels=labels)

        yield px
コード例 #9
0
    def draw(self):
        import networkx as nx
        import matplotlib.pyplot as plt
        from networkx.drawing.nx_pydot import graphviz_layout

        G = nx.DiGraph()
        labels = {}
        for p, edge in enumerate(self.edges):
            for s, q in enumerate(edge):
                if q == -1:
                    continue
                G.add_node(q)
                labels[q] = self.decode(s)
                # labels[q]=(self.decode(s),self.size[q])
                G.add_edge(p, q)

        pos = graphviz_layout(G, prog="dot")
        nx.draw(G, pos=pos, with_labels=True, labels=labels, node_size=1000)
        plt.axis("off")
        plt.show()
コード例 #10
0
ファイル: models.py プロジェクト: jfwilliams92/roots
    def update_node_positions(self, layout='dot'):
        """Utilizes networkx layout algorithms to determine optimal spacing of nodes."""

        """
        layout_map = {
            'spring': nx.spring_layout,
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spiral': nx.spiral_layout,
            'dot': nx.dot_layout
        }

        layout_func = layout_map[layout]
        node_positions = layout_func(self.graph_)
        """

        node_positiions = graphviz_layout(self.graph_, prog="twopi")

        for node_id, pos in node_positiions.items():
            self.graph_.nodes[node_id]['pos'] = pos
コード例 #11
0
def main():
    # Build a dataframe with 4 connections
    df = pd.DataFrame({
        'from': ['A', 'B', 'C', 'A'],
        'to': ['D', 'A', 'E', 'C']
    })

    # Build your graph
    G = nx.from_pandas_edgelist(df, 'from', 'to')
    pos = graphviz_layout(G, prog='twopi', args='')

    # Plot it
    nx.draw(G,
            pos,
            with_labels=True,
            node_color="skyblue",
            alpha=0.5,
            linewidths=40)
    plt.show()

    Jsonpath = 'C:/Users/edkaz/AppData/Local/Packages/f492410c-3390-4254-bf50-83137f1388b2_dv867kpbcjyry/LocalState/JSONs/testJSON.json'
コード例 #12
0
    def draw_graph(self):
        graph = self.nx_graph
        print(f"Nodes: {nx.number_of_nodes(graph)}\n"
              f"Edges: {nx.number_of_edges(graph)}\n"
              f"Connected Components: {nx.number_connected_components(graph)}")

        print(f"Saving graph to {self.name}.png...")
        plt.figure(1, figsize=(8, 8))
        conn_comps = nx.connected_component_subgraphs(graph)
        pos = graphviz_layout(graph)
        for g in conn_comps:
            node_color = [random.random()] * nx.number_of_nodes(g)
            nx.draw(g,
                    pos,
                    node_size=50,
                    node_color=node_color,
                    vmin=0.0,
                    vmax=1.0,
                    with_labels=False)

        plt.savefig(self.name)
コード例 #13
0
def plot_tree(graph, node_size=1000, font_size=12):
    graph = solve_graphviz_problems(graph)  ###

    pos = graphviz_layout(graph, prog='twopi', root=list(graph.nodes)[0])
    plt.figure(figsize=(10, 4), dpi=200)  ###
    plt.grid(b=None)  ### hide box
    plt.box(False)  ### hide grid
    plt_add_margin(pos)  ### just for layout

    colors = [graph.nodes[n]['dist'] for n in graph]  # colorize by distance
    nx.draw_networkx_nodes(graph,
                           pos,
                           node_size=node_size,
                           node_color=colors,
                           cmap='Set1',
                           alpha=0.4)
    nx.draw_networkx_labels(graph, pos, font_size=font_size)
    scale_weights(graph)  ### not in book

    for (n1, n2, sim) in graph.edges(data='sim'):
        nx.draw_networkx_edges(graph, pos, [(n1, n2)], width=sim, alpha=0.2)

    plt.show()
コード例 #14
0
    def draw(self) -> None:
        """A function draws a graph of the dynasty"""
        if len(self.edges) < 1:
            return
        graph = nx.DiGraph()

        son = [
        ]  # A list with all sons in the dynasty. Example [("mother", "son"), ("mother2", "son2")]
        for key, value in self.sons.items():
            for i in value:
                son.append((key, i))

        graph.add_nodes_from(self.people)
        graph.add_edges_from(list(self.marriages_w.items()) + son)

        pos = graphviz_layout(graph, prog="dot")

        labels = defaultdict(str)
        for node in graph.nodes():
            labels[node] = node

        color_map = {self.king: '#FF00FF'}

        colors = [color_map.get(node, '#FF0000') for node in graph.nodes()]
        nx.draw_networkx_nodes(graph, pos, self.people, 300, node_color=colors)
        nx.draw_networkx_labels(graph, pos, labels)
        nx.draw_networkx_edges(graph,
                               pos,
                               edgelist=list(self.marriages_w.items()),
                               edge_color='r',
                               arrows=False)
        nx.draw_networkx_edges(graph,
                               pos,
                               edgelist=son,
                               edge_color='b',
                               arrows=True)
        plt.show()
コード例 #15
0
def draw_graph_from_pandas(data):
    G = nx.from_pandas_adjacency(data, create_using=nx.DiGraph())

    edge_colors = [edge['weight'] for _, edge in G.edges.items()]

    pos = graphviz_layout(G, prog="sfdp")
    plt.figure(figsize=(8, 4), dpi=100)

    nx.draw(G, pos, with_labels=True, edgelist=[])

    edges = nx.draw_networkx_edges(G,
                                   pos,
                                   arrowstyle="->",
                                   arrowsize=10,
                                   edgelist=G.edges().keys(),
                                   edge_color=edge_colors,
                                   edge_cmap=plt.cm.Blues,
                                   width=2,
                                   connectionstyle='arc3, rad = 0.1')

    pc = mpl.collections.PatchCollection(edges, cmap=plt.cm.Blues)
    pc.set_array(edge_colors)
    plt.colorbar(pc)
    plt.show()
コード例 #16
0
def plotGraph(logger, graph, fileName=None):
    '''plot the graph
    
    Parameters
    ----------
    logger : {logging.logger}
        logging element 
    graph : {networkX.Graph object}
        The graph that needs to be plotted
    fileName : {str}, optional
        name of the file where to save the graph (the default is None, which
        results in no graph being generated)
    '''

    try:
        plt.figure()

        moduleNodes = [m for m, d in graph.nodes(data=True) if ('module' == d['type'])]
        otherNodes  = [m for m, d in graph.nodes(data=True) if ('module' != d['type'])]
        lables      = {m:m for m in graph.nodes}

        pos = graphviz_layout(graph, prog='dot')
        nx.draw_networkx_nodes(graph, pos, nodelist=moduleNodes, node_color='orange', node_size=500)
        nx.draw_networkx_nodes(graph, pos, nodelist=otherNodes, node_color='cyan', node_size=500)
        nx.draw_networkx_edges(graph, pos,  arrows=True)
        nx.draw_networkx_labels(graph, pos, lables, font_size=10)

        if fileName is not None:
            plt.savefig(fileName)

        plt.close()
        print('Graph saved ...')
    except Exception as e:
        logger.error('Unable to plot the graph: {}'.format(e))

    return
コード例 #17
0
def Draw_2(G, df):
    '''

    :param G:
    :param df:
    :return:
    '''

    key_nodes = args.key_nodes  #画出的跟结点
    if len(key_nodes) != 0:
        nodes = []
        for item in key_nodes:
            nodes.append(get_children(item))
        all_nodes = merge_list(nodes) + key_nodes
        del (nodes)

        # all_nodes = merge_list2(nodes[0],nodes[1])

        # (all_nodes)
        print(len(all_nodes))
        sub_g = G.subgraph(all_nodes)
        G = nx.MultiDiGraph(sub_g)
    else:
        pass

    in_deg = [item for item in G.in_degree]
    in_deg = dict(in_deg)
    out_deg = [item for item in G.out_degree]
    out_deg = dict(out_deg)

    # REMOVE NODES
    Gnodes = list(G.nodes)  # deep copy
    if args.show_leaf == False:
        for node in Gnodes:
            if node[:2] == '.0' and in_deg[node] < draw_th:
                G.remove_node(node)
        print('AFTER REMOVE')
    else:
        print('SHOW LEAF')

    print(len(G.nodes))
    print(len(G.edges))

    # define key edges
    key_edges = []
    for (o, i, j) in G.edges:
        if is_leaf(i) == False:  # 如果边的入结点不是叶子, 那边就是干
            key_edges.append((o, i, j))

    # with labels, 显示中文结点名字
    words = {}
    for idx, row in df.iterrows():
        pass
        words[row['id']] = row['word']
    labels = {}
    for id in G.nodes:
        #        labels[id] = id  # named as id
        labels[id] = words[id]  # df['id'].at(node)

    # 1. node color size
    node_color = []
    node_size = []
    for node in G.nodes():
        ns = in_deg[node]
        node_size.append(ns)
        c = cnt_sub_nodes(node)
        node_color.append(c)
    node_size = np.array(node_size) * 200 + 200
    node_color = np.array(node_color)

    # edge color size
    edge_width = []
    edge_color = []
    for (x, y, i) in G.edges:
        c = cnt_sub_nodes(y)
        edge_width.append(c)
        if is_leaf(y):
            edge_color.append('lightskyblue')
        else:
            edge_color.append('red')

    edge_width = np.array(edge_width)

    min = edge_width.min()
    max = edge_width.max()
    if min != max:
        edge_width = (edge_width - min) / (max - min)
    else:
        pass
    edge_width = 2 * edge_width + 1

    if len(key_nodes) == 1:
        edge_width = 1
    # draw
    # pos = nx.spring_layout(G)
    pos = graphviz_layout(G, prog='sfdp')
    # pos = nx.spectral_layout(sub_g)
    # print(edge_width)
    # print(edge_color)
    # print(node_color)
    # print(node_size)
    nx.draw(
        G,
        pos,
        cmap=plt.get_cmap('Wistia'),
        node_color=node_color,  # same size with nodes
        node_size=node_size,
        # edge
        edge_color=edge_color,
        # edge_cmap=plt.get_cmap('Blues'),
        width=edge_width,
        # label_color='white',
        labels=labels,
        encoding='utf-8',
        with_labels=True)
    plt.axis('off')
    plt.show()
コード例 #18
0
def Draw_1(G, df):
    '''

    :param G:
    :param df:
    :return:
    '''
    plt.style.use('dark_background')

    #key_nodes=['.1.01','.1.00','.1.03','.1.05']
    #key_nodes=['.1.01','.1.00','.1.03','.1.05']# doc6 病原学特点, 流行病学特点,诊断标准
    #key_nodes=['.1.01','.1.00']

    nodes = []
    for item in key_nodes:
        nodes.append(get_children(item))
    all_nodes = merge_list(nodes) + key_nodes
    del (nodes)

    #all_nodes = merge_list2(nodes[0],nodes[1])

    #(all_nodes)
    sub_g = G.subgraph(all_nodes)
    sub_g = nx.MultiDiGraph(sub_g)

    in_deg = [item for item in sub_g.in_degree]
    in_deg = dict(in_deg)

    out_deg = [item for item in sub_g.out_degree]
    out_deg = dict(out_deg)

    nodes = list(sub_g.nodes())
    for node in nodes:
        if node[:2] == '.0' and in_deg[node] < 2:
            sub_g.remove_node(node)
    print('sub graph')
    print(len(sub_g.nodes))
    print(len(sub_g.edges))

    # define key edges
    key_edges = []
    for (o, i, j) in sub_g.edges:
        if is_leaf(i) == False:  # 如果边的入结点不是叶子, 那边就是干
            key_edges.append((o, i, j))
    print(key_edges)

    #with labels

    labels = {}
    for node in sub_g.nodes:
        labels[node] = node  # df['id'].at(node)
#1. node color
    node_color = []
    for node in sub_g.nodes:
        node_color.append(in_deg[node])
#        if is_leaf(node) == False:
#            node_color.append('red')
#            with_labels.append(True)
#        else:
#            node_color.append('yellow')
#            with_labels.append(False)
#2. node size
    base_size = 350
    k = 200
    node_size = []
    for item in sub_g.nodes:
        #        if is_leaf(item) ==True:
        node_size.append(cnt_sub_nodes(item))
        #            node_size.append(base_size)
        node_size = normalize(node_size)
#edge color, width

# for edge in sub_g.edges:
#     if edge in key_edges:
#         edge_width.append(4)
#         edge_color.append('blue')

#     else:
#         edge_width.append(0.5)
#         edge_color.append('gray')

    edge_width = []
    edge_color = []
    base_width = 1
    base_edge_color = 1
    for (x, y, i) in sub_g.edges:
        c = cnt_sub_nodes(y)
        edge_width.append(c)
        if is_leaf(y):
            edge_color.append('lightskyblue')
        else:
            edge_color.append('deepskyblue')
        #edge_width.append(c*base_width+base_width)


#edge_width
#edge_color = recolor(edge_color)

    pos = graphviz_layout(sub_g, prog='fdp')
    #pos = nx.spectral_layout(sub_g)
    nx.draw(
        sub_g,
        pos,
        cmap=plt.get_cmap('Wistia'),
        node_color=node_color,  # same size with nodes
        node_size=node_size,
        #edge
        edge_color=edge_color,
        #edge_cmap=plt.get_cmap('Blues'),
        width=edge_width)
    #label_color='white',
    #labels = labels,
    #with_labels=True)
    plt.axis('off')
    plt.show()
コード例 #19
0
 def layout(self, root):
     """ Slowly sets node positions using graphviz, with given root. """
     for node, (x, y) in graphviz_layout(self, 'dot', root).items():
         self.nodes[node]['viz']['position'] = {'x': x, 'y': y, 'z': 0}
コード例 #20
0
ファイル: pfsg.py プロジェクト: niveknosredneh/PFSG
        if p.memory_percent() < 1: mem = ""
        else: mem = f"{int(p.memory_percent())}%"
        G.add_node(p.pid,
                   size=1,
                   file='False',
                   depth=nx.shortest_path_length(G, root.pid,
                                                 p.parent().pid),
                   label=f"{p.name()} {mem}")
        if not (p.parent() is None): G.add_edge(p.pid, p.parent().pid, depth=3)

        #par = p.parent().pid
        #while par is not root.pid:

print("Calculating Layout ...")
pos = graphviz_layout(G, prog=layout)  #, root=1) # use layout
fig = plt.figure(figsize=(width / 100.0, height / 100.0))  # set figure size

# DRAW
print("Drawing Graph ...")
#nodes
node_depths = nx.get_node_attributes(G, 'depth')
edge_depths = nx.get_edge_attributes(G, 'depth')
node_labels = nx.get_node_attributes(G, 'label')
edge_labels = nx.get_edge_attributes(G, 'label')
node_sizes = nx.get_node_attributes(G, 'size')
edge_sizes = nx.get_edge_attributes(G, 'size')
is_file = nx.get_node_attributes(G, 'file')

vmin = 0
if map_by_size: vmax = largest + int(colourmap_soften)
コード例 #21
0
ファイル: weaver.py プロジェクト: SHZ66/HiDeF
def show_hierarchy(T, **kwargs):
    """Visualizes the hierarchy"""

    from networkx.drawing.nx_pydot import write_dot, graphviz_layout
    from networkx import draw, get_edge_attributes, draw_networkx_edge_labels
    from os import name as osname

    from matplotlib.pyplot import plot, xlim, ylim

    style = kwargs.pop('style', 'dot')
    style = kwargs.pop('layout', style)
    leaf = kwargs.pop('leaf', True)
    nodesize = kwargs.pop('node_size', 16)
    edgescale = kwargs.pop('edge_scale', None)
    edgelabel = kwargs.pop('edge_label', False)
    interactive = kwargs.pop('interactive', True)
    excluded_nodes = kwargs.pop('excluded_nodes', [])
    node_color = kwargs.pop('node_color', '#1f78b4')
    with_colors = kwargs.pop('with_colors', False)

    isWindows = osname == 'nt'

    pos = None
    if isinstance(style, str):
        if isWindows:
            style += '.exe'
    elif isinstance(style, dict):
        pos = style
    else:
        raise TypeError('unknown style: ' + str(style))

    if not leaf:
        T2 = T.subgraph(n for n in T.nodes()
                        if isinternal(T, n) and n not in excluded_nodes)
        if 'nodelist' in kwargs:
            nodes = kwargs.pop('nodelist')
            nonleaves = []
            for node in nodes:
                if isinternal(T, node) and node not in excluded_nodes:
                    nonleaves.append(node)
            kwargs['nodelist'] = nonleaves
    else:
        T2 = T.subgraph(n for n in T.nodes() if n not in excluded_nodes)

    nodelist = kwargs.pop('nodelist', T2.nodes())
    if with_colors:
        node_colors = []

        for node in nodelist:
            if 'color' in T2.nodes[node]:
                node_colors.append(T2.nodes[node]['color'])
            else:
                node_colors.append(node_color)
    else:
        node_colors = node_color

    if pos is None:
        pos = graphviz_layout(T2, prog=style)

    if edgescale:
        widths = []
        for u, v in T2.edges():
            w = T2[u][v]['weight'] * edgescale
            widths.append(w)
    else:
        widths = 1.

    if not 'arrows' in kwargs:
        kwargs['arrows'] = False

    draw(T2,
         pos,
         node_size=nodesize,
         width=widths,
         node_color=node_colors,
         nodelist=nodelist,
         **kwargs)

    if edgelabel:
        labels = get_edge_attributes(T2, 'weight')
        draw_networkx_edge_labels(T2, pos, edge_labels=labels)

    if interactive:
        from matplotlib.pyplot import gcf
        from scipy.spatial.distance import cdist

        annotations = {}

        def _onclick(event):
            ax = event.inaxes
            if ax is not None:
                if event.button == 1:
                    view = ax.viewLim.extents
                    xl = (view[0], view[2])
                    yl = (view[1], view[3])
                    xl, yl = ax.get_xlim(), ax.get_ylim()
                    x_, y_ = event.xdata, event.ydata

                    dx = (xl[1] - xl[0]) / 20
                    dy = (yl[1] - yl[0]) / 20
                    dr = min((dx, dy))

                    nodes = []
                    coords = []
                    for node, coord in pos.items():
                        nodes.append(node)
                        coords.append(coord)

                    D = cdist([(x_, y_)], coords).flatten()
                    i = D.argmin()

                    if D[i] < dr:
                        x, y = coords[i]
                        node = nodes[i]

                        if node not in annotations:
                            #ax.plot([i, i], ax.get_ylim(), 'k--')
                            l = ax.plot([x], [y],
                                        'bo',
                                        fillstyle='none',
                                        markersize=nodesize // 2)
                            t = ax.text(x, y, str(node), color='k')
                            annotations[node] = (l[0], t)
                            xlim(xl)
                            ylim(yl)
                        else:
                            l, t = annotations.pop(node)
                            ax.lines.remove(l)
                            ax.texts.remove(t)
                elif event.button == 3:
                    for node in annotations:
                        l, t = annotations[node]
                        ax.lines.remove(l)
                        ax.texts.remove(t)
                    annotations.clear()
                fig.canvas.draw()

        fig = gcf()
        cid = fig.canvas.mpl_connect('button_press_event', _onclick)

    return T2, pos
コード例 #22
0
def show_tree(model, ticklabels):
    import matplotlib.pyplot as plt
    import networkx as nx
    import pygraphviz

    # try:
    # 	import pygraphviz
    # 	from networkx.drawing.nx_agraph import graphviz_layout
    # except ImportError:
    # 	pass
    # try:
    # 	import pydot
    # 	from networkx.drawing.nx_pydot import graphviz_layout
    # except ImportError:
    # 	raise ImportError("This example needs Graphviz and either "
    # 											"PyGraphviz or pydot")

    from networkx.drawing.nx_pydot import graphviz_layout

    n_instances = model.children_.shape[0]
    counts = np.zeros(n_instances)
    n_samples = len(model.labels_)
    for i, merge in enumerate(model.children_):
        current_count = 0
        for child_idx in merge:
            if child_idx < n_samples:
                current_count += 1  # leaf node
            else:
                current_count += counts[child_idx - n_samples]
        counts[i] = current_count
    linkage_matrix = np.column_stack(
        [model.children_, model.distances_, counts]).astype(float)

    G = nx.Graph()
    parent_node = n_instances

    color_map = []

    rootnode, nodelist = hierarchy.to_tree(linkage_matrix, rd=True)
    # print (rootnode)
    # print (nodelist)
    node_dict = dict({})
    for nd in nodelist:
        #     print(nd.id, nd.get_count())
        node_dict[nd.id] = nd.get_count()

    for node_1, node_2, distance, n_ele in linkage_matrix:
        node_1 = int(node_1)
        node_2 = int(node_2)
        n_ele = int(n_ele)

        #     print (node_1, node_2, distance, n_ele)
        #     print (node_1, node_dict[node_1], node_2, node_dict[node_2])
        if node_1 < n_instances:
            G.add_node(node_1, label=ticklabels[node_1])
            color_map.append("red")
        if node_2 < n_instances:
            G.add_node(node_2, label=ticklabels[node_2])
            color_map.append("red")
        if n_ele == n_instances:
            G.add_node(parent_node, label="Root")
            color_map.append("orange")
        else:
            G.add_node(parent_node, label="")  # parent_node
            color_map.append("green")

        # weight_n1 = transform(x=node_dict[node_1] /int(n_instances))
        # weight_n2 = transform(x=node_dict[node_2] /int(n_instances))

        weight_n1 = 1
        weight_n2 = 1

        G.add_edge(
            parent_node, node_1,
            weight=weight_n1)  # 1 - np.log(weight_n1), distance, 30*weight_n1
        G.add_edge(parent_node, node_2,
                   weight=5 * weight_n2)  # 1 - np.log(weight_n2), distance
        parent_node += 1

    pos = graphviz_layout(G)  #  prog='twopi'
    fig = plt.figure(figsize=(16, 16))

    weights = [G[u][v]['weight'] for u, v in G.edges()]
    # d = nx.degree(G) node_size=[v * 1000 for v in d],
    nx.draw(G, pos, node_color=color_map, width=weights)

    node_labels = nx.get_node_attributes(G, 'label')

    nx.draw_networkx_labels(G,
                            pos,
                            labels=node_labels,
                            width=weights,
                            font_size=18)
    plt.title("Circular Tree - 2D HAC visualization")
    plt.axis('equal')
    plt.savefig("test.pdf")
コード例 #23
0
    figure(**figureinfo)
    subplot(111)
    if graphname == 'Graph' or graphname == 'BST':
        T = Graph(**graphinfo)
    elif graphname == 'DiGraph':
        T = DiGraph(**graphinfo)
    else:
        T = Graph(**graphinfo)
    if graphname=='BT':
        for i in nodeinfo.keys():
            T.add_node(i,child_status=nodeinfo[i][1])
            nodeinfo[i]=nodeinfo[i][0]
    else:
        for i in nodeinfo.keys():
            T.add_node(i)
    for i in edgeinfo:
        T.add_edge(*i)
    if uselayout=='graphviz':
        pos = graphviz_layout(T, **layoutinfo)
    elif uselayout=='bt':
        pos = binary_tree_layout(T,**layoutinfo)
    elif uselayout=='joel':
        pos = hierarchy_pos(T, **layoutinfo)
    elif uselayout=='joel2':
        pos = hierarchy_pos2(T, **layoutinfo)
    else:
        pos=None
    draw(T, pos, labels=nodeinfo, **drawinfo)
    show()
    sys.exit(0)
コード例 #24
0
ファイル: bb_tree_old.py プロジェクト: andygaspar/xpress
def bb(A, b):
    T = nx.Graph()
    tree_idx = 0

    pb = xp.problem()
    x_lp = np.array([xp.var(vartype=xp.continuous) for _ in range(A.shape[1])])
    pb.addVariable(x_lp)
    pb.addConstraint(xp.Dot(A, x_lp) <= b)
    pb.setObjective(xp.Dot(c, x_lp), sense=xp.maximize)

    lb_node = Node(xp.problem(), -1)

    root_node = Node(pb, tree_idx)
    T.add_node(tree_idx)

    is_integer, is_infeasible = root_node.solve()
    if is_integer:
        return root_node.pb.getObjVal(), root_node.pb.getSolution()
    elif is_infeasible:
        return False, False

    l_node, r_node = root_node.make_sub_problems(tree_idx)

    active_nodes = [l_node, r_node]
    T.add_node(l_node.tree_idx)
    T.add_node(r_node.tree_idx)
    T.add_edge(root_node.tree_idx, l_node.tree_idx)
    T.add_edge(root_node.tree_idx, r_node.tree_idx)
    tree_idx += 3

    while True:

        not_pruned_nodes = []
        for node in active_nodes:
            is_integer, is_infeasible = node.solve()
            if is_integer:
                if node.objVal > lb_node.objVal:
                    lb_node = node
            elif not is_infeasible:
                not_pruned_nodes.append(node)

        if is_optimal(lb_node, not_pruned_nodes):
            pos = graphviz_layout(T, prog="dot")
            print(pos)
            labels = pos
            print(labels)
            nx.draw(T, pos)
            nx.draw_networkx_labels(T, pos, labels)
            plt.show()
            return lb_node.pb.getObjVal(), lb_node.pb.getSolution()

        active_nodes = []
        for node in not_pruned_nodes:
            l_node, r_node = node.make_sub_problems(tree_idx)
            active_nodes.append(l_node)
            active_nodes.append(r_node)
            T.add_node(l_node.tree_idx)
            T.add_node(r_node.tree_idx)
            T.add_edge(node.tree_idx, l_node.tree_idx)
            T.add_edge(node.tree_idx, r_node.tree_idx)
            tree_idx += 3
コード例 #25
0
def tree_alignment(
    aligned_data: CapitalData,
    figsize: tuple = (10, 8),
    node_size: int = 1200,
    font_size: int = 18,
    dpi: int = 600,
    show: bool = True,
    save: Union[str, bool] = False,
):
    """\
    Plot the alignment of the trees.

    Parameters
    ----------
    aligned_data : CapitalData
        [description]
    figsize : tuple
        [description], by default (10, 8).
    node_size : int
        [description], by default 1200.
    font_size : int
        [description], by default 18.
    show : bool,
        If `True`, show the figure. If `False`, return figure, by default `True`.
    save : Union[str, bool]
        If `True` or `str`, save the figure. If a path is specified as `str`, the figure is saved in the path, by default `None`.
    """

    if not isinstance(aligned_data, CapitalData):
        ValueError("draw_alignmenttree() expects an CapitalData argument.")

    tree = aligned_data.alignedtree
    mapping = {
        i: str(i).replace("'", "").replace("(", "").replace(")", "")
        for i in tree.nodes()
    }
    tree = nx.relabel_nodes(tree, mapping)
    plt.figure(figsize=figsize)
    pos = graphviz_layout(tree, prog='dot')
    nx.draw(tree,
            pos,
            node_color='lightskyblue',
            font_weight='bold',
            font_size=font_size,
            node_size=node_size,
            with_labels=True,
            edge_color="gray",
            arrows=True)

    if save:
        if isinstance(save, str):
            save_dir = save
            os.makedirs(os.path.dirname(save_dir), exist_ok=True)
        elif save is True:
            os.makedirs("./figures", exist_ok=True)
            save_dir = "./figures/alignmenttree.png"
        plt.savefig(save_dir, bbox_inches='tight', pad_inches=0.1, dpi=dpi)
    if show:
        plt.show()
    else:
        plt.close()
    plt.close()
コード例 #26
0
ファイル: FileAnalyser.py プロジェクト: AbhiDasari/tool2
plt.title('Extension Treemap by Size')
plt.axis('off')
plt.savefig("C:\\Users\\761317\Desktop\\Code Comparision\\Results\\size_distribution.jpg", bbox_inches="tight")
####################################################################



####################################################################
import networkx as nx

# Sort the index
data_sorted = data.sort_values(by='id')

G = nx.Graph()
for i, row in data_sorted.iterrows():
    if row.parent:
        G.add_edge(row.id, row.parent)
    
# Print some additional information
print(nx.info(G))
####################################################################

from networkx.drawing.nx_pydot import graphviz_layout

pos_dot = graphviz_layout(G, prog='dot')

fig = plt.figure(figsize=(16, 8))
nodes = nx.draw_networkx_nodes(G, pos_dot, node_size=2, node_color='C0')
edges = nx.draw_networkx_edges(G, pos_dot, edge_color='C0', width=0.5)
plt.axis('off');
コード例 #27
0
ファイル: dpop_v2.py プロジェクト: vassilispapadop/dcop
def main():
    # 1st row: Number of agents;Number of meetings;Number of variables
    useAgents = True
    # Open file 
    # inputFilename = 'constraint_graphs/dcop_constraint_graph'
    # inputFilename = 'constraint_graphs/dcop_simple'
    inputFilename = 'constraint_graphs/DCOP_Problem_300'
    input = open(inputFilename, 'r') 
    
    # Read first line
    [nrAgents, nrMeetings, nrVars] = uv2.readLine(input)
    print("Number of agents:%d \nNumber of meetings:%d \nNumber of variables:%d" %(nrAgents, nrMeetings, nrVars))

    # Read variables
    global agentsList
    varList, agentsList = uv2.readVariables(input, nrVars)

    # Read preference
    agentsList = uv2.readPrerefence(input, agentsList)

    # Create internal/node matrix per meeting
    agentsList = uv2.buildPrefMatrixInternal(agentsList)

    print('-----------Variables Graph--------------')   
    graphVariables = {}
    for v in varList:
        graphVariables[v.varId] = ptree.getAllVarsWithSameMeeting(varList, v.meetingId, v.varId)

    print (graphVariables) 

    print('-----------Agents Graph--------------')  
    graphAgents = {}
    for id, attr in agentsList.items():
        graphAgents[id] = ptree.getAllAgentsWithSameMeeting(agentsList, attr.meetings, id)

    print (graphAgents)
    graph = graphVariables
    if useAgents == True:
        graph = graphAgents

    # Add all edges to graph
    graph_edges = []
    for k, l in graph.items():
        for v in l:
            graph_edges.append((k,v))
    graph_edges = [list(tpl) for tpl in list(set([tuple(sorted(pair)) for pair in graph_edges]))]
    print(graph_edges)

    # Create graph
    G = nx.Graph()
    
    # Constraint graph
    for e in graph_edges:
        G.add_edge(*e, color = 'black')


    layout = graphviz_layout(G, prog="dot") 
    nx.draw(G, layout, with_labels=True, node_color='#efedf2', arrowsize=1)#, connectionstyle="arc3,rad=0.1"
    output = "root_"+str(root_node)+".png"
    plt.savefig(output, format="PNG")

    # Create dfs tree with speficied node
    TreeDfs = nx.dfs_tree(G, root_node)

    print("----------------")
    back_edges = []
    for node, connected in graph.items():
        e = set(TreeDfs.edges([node]))
        shouldBe = []
        for con in connected:
            if (node, con) in e: continue
            if (con, node) in e: continue
            if TreeDfs.has_edge(node,con): continue
            if TreeDfs.has_edge(con,node): continue

            shouldBe.append((node, con))

        back = set(shouldBe) - e
        back_edges.append(back)


    back_edges = [item for sublist in back_edges for item in sublist]
    back_edges = [list(tpl) for tpl in list(set([tuple(sorted(pair)) for pair in back_edges]))]
    print(back_edges)
    for e in back_edges:
        TreeDfs.add_edge(*e, color = 'blue', style='dashed')


    # create relations based on tree edges
    create_relations(TreeDfs, agentsList)

    # find leaves in order to start compute util process
    leaves = find_leave_nodes(TreeDfs)     

    edges = TreeDfs.edges.data('color', default='black')
    colors = []
    for _,_,c in edges:
        colors.append(c)

    # layout = graphviz_layout(TreeDfs, prog="dot") 
    # nx.draw(TreeDfs, layout, edge_color=colors, with_labels=True, node_color='#efedf2', arrowsize=1)#, connectionstyle="arc3,rad=0.1"
    # output = "root_"+str(root_node)+".png"
    # plt.savefig(output, format="PNG")

    # print(nx.shortest_path_length(TreeDfs,root_node))
    print("Leaves are:", leaves)
    send_util_msg(TreeDfs, leaves, msgCounter, msgSizePerCycleCounter, cycleCounter)
    send_value_msg()

    #Constraints = Number of edges + Inequality constraints
    EQConstraints = TreeDfs.number_of_edges()
    #iterate through every agent and count number of inequality constraints
    NEQConstraints = 0
    for id, attr in agentsList.items():
        i = len(attr.meetings) - 1
        count = 0
        while i > 0:
            count += i
            i -= 1
        NEQConstraints += count

    # Print table results, as in paper
    print("Number of agents:%d \nNumber of meetings:%d \nNumber of variables:%d" %(nrAgents, nrMeetings, nrVars))
    print("Total Constraints", EQConstraints+NEQConstraints)
    print("\tEquality constraints", EQConstraints)
    print("\tInequality constraints", NEQConstraints)
    print("Total number of messages:%d" %(len(msgCountPerIteration) * 2))
    print("Max message size:%d"% (max(MESSAGES_SIZE)))
    print("Cycles:%d"% (len(cyclePerLevel) * 2))
コード例 #28
0
 def visualize(self):
     g = self.create_nx_tree()
     pos = graphviz_layout(g, prog="dot")
     nx.draw(g, pos, with_labels=True)
     plt.savefig("tree.png")
コード例 #29
0
        # Glycan is not attached to an amino acid -> Ignore glycan
        continue
    else:
        root = root[0]
    glycosylated_residue_ids.append(root)
    glycosylated_residue_symbols.append(
        seq.ProteinSequence.convert_letter_3to1(ids_to_names[root]))

    # The saccharide directly attached to the amino acid
    root_neighbor = list(glycan_graph.neighbors(root))[0]

    # Position the nodes for the plot:
    # Create an initial tree layout and transform it afterwards,
    # so that each glycan graph is at the correct position and the
    # node distances are equal
    pos = graphviz_layout(glycan_graph, prog="dot")
    nodes = list(pos.keys())
    # Convert dictionary to array
    pos_array = np.array(list(pos.values()))
    # Position the root at coordinate origin
    pos_array -= pos_array[nodes.index(root)]
    # Set vertical distances between nodes to 1
    pos_array[:, 1] /= (pos_array[nodes.index(root_neighbor), 1] -
                        pos_array[nodes.index(root), 1])
    # Set minimum horizontal distances between nodes to 1
    non_zero_dist = np.abs(pos_array[(pos_array[:, 0] != 0), 0])
    if len(non_zero_dist) != 0:
        pos_array[:, 0] *= HORIZONTAL_NODE_DISTANCE / np.min(non_zero_dist)
    # Move graph to residue ID position on x-axis
    pos_array[:, 0] += root
    # Convert array back to dictionary
コード例 #30
0
    def _draw_plot(self, fig=None, ax=None):
        import networkx as nx
        from networkx.drawing.nx_pydot import graphviz_layout, pydot_layout
        from matplotlib.patches import FancyArrowPatch

        graph = self.graph

        # Graphviz is a pain to install in Windows and may not be available.
        # Spring layout is awful, but at least is guaranteed to work.
        try:
            pos = graphviz_layout(graph)
        except:
            pos = nx.spring_layout(graph, iterations=20)

        fig, ax = self._get_fig_ax(fig, ax)

        # We are not plotting actual values, hide both axis.
        ax.axis('off')

        # Automatically show labels for small networks.
        if self.with_labels is None and len(self.data) < 10:
            self.with_labels = True

        # Increase node size to fit labels.
        if self.node_size is None:
            if self.with_labels:
                self.node_size = 300
            else:
                self.node_size = 20

        nx.draw_networkx_edges(graph, pos, ax=ax, arrows=False)

        if self.directed:
            # Networkx default "directed" visualization just draws a thicker stub at the end.
            # This code adds actual arrow heads, taking care not to overlap the nodes themselves.
            for start, end in self.data:
                if start == end:
                    continue
                start_x, start_y = pos[start]
                end_x, end_y = pos[end]
                angle = math.atan2(end_y - start_y, end_x - start_x)
                distance = math.sqrt((end_x - start_x)**2 +
                                     (end_y - start_y)**2)
                end_pos = (end_x - 0.1 * distance * math.cos(angle),
                           end_y - 0.1 * distance * math.sin(angle))
                ax.add_patch(
                    FancyArrowPatch(posA=(start_x, start_y),
                                    posB=end_pos,
                                    color='k',
                                    arrowstyle=self.arrowstyle,
                                    mutation_scale=30,
                                    connectionstyle="arc3"))

        nx.draw_networkx_nodes(graph,
                               pos,
                               node_size=self.node_size,
                               ax=ax,
                               node_color=self.node_color,
                               cmap=self.cmap)

        if self.with_labels:
            if max(len(str(l)) for l in pos) <= 2:
                nx.draw_networkx_labels(graph,
                                        pos,
                                        fontsize=self.fontsize,
                                        ax=ax)
            else:
                # Large labels don't look because they don't fit. In that case
                # we draw them outside the node, slightly above, with a white
                # box behind.
                for label, (x, y) in pos.items():
                    ax.text(x,
                            y + self.fontsize,
                            label,
                            ha='center',
                            fontsize=self.fontsize,
                            bbox={
                                'color': 'white',
                                'alpha': 1
                            })

        if fig:
            # Resize plot to fill available space.
            fig.tight_layout()
コード例 #31
0
ファイル: create_tree.py プロジェクト: tazmanian60/bcosv
    if start[0]!=' ':
        l = 0
    elif start[4]!=' ':
        l = 1
    elif start[8]!=' ':
        l = 2
    elif start[12]!=' ':
        l = 3
    elif start[16]!=' ':
        l = 4
    else:
        l =5

    name = ch1[1].split(',')[0].replace('"','').replace('\'','')
    G.add_node(name,l=l)
    if l!=lprev:
        d[l]=name
    if l>0:
        G.add_edge(name,d[l-1])
    lprev = l

from networkx.drawing.nx_pydot import graphviz_layout
pos=graphviz_layout(G,prog='twopi',args='')
#pos=nx.spring_layout(G)
fig = plt.figure(figsize=(20,20))
nx.draw(G,pos,node_size=20,alpha=0.5,node_color='blue',with_labels=True,fig=fig)
plt.savefig('tabbyGraph.png')
for n in G.nodes_iter():
    if G.node[n]['l']==1:
        print n
コード例 #32
0
def main(plot_subtrees,
         prog='twopi',
         save_fig=True,
         similarity_edges=None,
         include_root=False):
    # Initialise graph
    G = nx.Graph()  #DiGraph()

    # Load file
    #url = 'https://biobank.ctsu.ox.ac.uk/crystal/coding.cgi?id=19&nl=1'
    dir = Path(r"C:\Users\Jacob\Downloads\autoencoders")
    file = dir / "coding19.tsv"

    # Load file as dataframe
    df = pd.read_csv(file, sep='\t')

    # Generate nodes and edges from file
    edges = list(zip(df['parent_id'], df['node_id']))

    # Add edges to graph
    if include_root:
        G.add_edges_from(edges)
    else:
        G.add_edges_from([edge for edge in edges if 0 not in edge])

    if plot_subtrees:
        # Create unrooted subtrees
        G2 = nx.Graph()
        G2.add_edges_from([edge for edge in G.edges if 0 not in edge])

        # Plot graph
        fig, axes = plt.subplots(nrows=6,
                                 ncols=4,
                                 sharey=True,
                                 sharex=True,
                                 figsize=(16, 24))
        ax = axes.flatten()

        for j, c in enumerate(nx.connected_components(G2)):
            root = min(c)
            edges = set(
                [edge for edge in G2.edges for node in c if node in edge])
            graph = nx.Graph()
            graph.add_edges_from(edges)
            pos = graphviz_layout(graph, prog=prog, root=root, args='')

            nx.draw(graph,
                    pos,
                    node_size=2,
                    alpha=0.5,
                    node_color="#00B7EB",
                    with_labels=False,
                    ax=ax[j],
                    arrowstyle='-')
            ax[j].set_axis_off()

    else:
        # Use radial tree representation
        pos = graphviz_layout(G, prog=prog, root=0, args='')
        #nx.draw(G, pos, node_size=0.5, alpha=0.5, node_color="#00B7EB",
        #        with_labels=False, arrowstyle='-')

    if similarity_edges:
        G = add_similarity_edges(G, similarity_edges, df)

    timestamp = datetime.now().strftime("%d-%b-%Y-%H%M%S)")

    # Save figure
    if save_fig:
        plt.savefig(dir / f"plot_{timestamp}.png", dpi=2000, figsize=(120, 20))
    plt.show()

    return G, pos, df
コード例 #33
0
    def plot_graph(
        self,
        g,
        filename,
        title,
        node_size=500,
        label_font_size=12,
        text_angle=0,
        image_width=16,
        image_height=12,
    ):
        """plot the graph and write to file
        Args:
            g (networkx): networkx graph object
            filename (str): path to write image to
            title (str): title to add to chart
            node_size (int): node size 
            label_font_size (int): font size
            text_angle (int): angle to rotate. This is angle in degrees counter clockwise from east 
            image_width (int): width of image in inches 
            image_height (int): heightof image in inches
        Returns:
            nothing but does write image to file
        """
        # map nodes to a color for their node type
        # https://stackoverflow.com/questions/27030473/how-to-set-colors-for-nodes-in-networkx-python
        color_map = []
        colors = ["#b3cde3", "#ccebc5", "#decbe4", "#FFA500"]
        for node in g:
            if self.node_map[node] == NodeType.MODEL:
                color_map.append(colors[0])
            elif self.node_map[node] == NodeType.EXPLORE:
                color_map.append(colors[1])
            elif self.node_map[node] == NodeType.VIEW:
                color_map.append(colors[2])
            else:
                color_map.append(colors[3])

        fig = plt.figure(figsize=(image_width, image_height))
        ax = plt.subplot(111)

        try:
            import pydot
            from networkx.drawing.nx_pydot import graphviz_layout
        except ImportError:  # pragma: no cover
            raise ImportError(
                "Requires Graphviz and either PyGraphviz or pydot"
            )  # pragma: no cover

        # pos = nx.spring_layout(g)
        # pos = nx.circular_layout(g)
        # pos = nx.kamada_kawai_layout(g)
        # pos = nx.shell_layout(g)
        # pos = nx.spectral_layout(g)
        pos = graphviz_layout(g, prog="dot", seed=42)
        nx.draw(
            g,
            pos,
            node_size=node_size,
            node_color=color_map,
            edge_color="#939393",
            font_size=9,
            font_weight="bold",
        )

        text = nx.draw_networkx_labels(
            g, pos, with_labels=False, font_size=label_font_size
        )
        for _, t in text.items():
            t.set_rotation(text_angle)

        plt.axis("off")
        plt.title(title, fontsize=20)
        plt.tight_layout()
        plt.savefig(filename, format="PNG")
        log.info("Graph written to %s", filename)
コード例 #34
0
ファイル: __init__.py プロジェクト: boppreh/sciplot
    def _draw_plot(self, fig=None, ax=None):
        import networkx as nx
        from networkx.drawing.nx_pydot import graphviz_layout, pydot_layout
        from matplotlib.patches import FancyArrowPatch

        graph = self.graph

        # Graphviz is a pain to install in Windows and may not be available.
        # Spring layout is awful, but at least is guaranteed to work.
        try:
            pos = graphviz_layout(graph)
        except:
            pos = nx.spring_layout(graph, iterations=20)
            
        fig, ax = self._get_fig_ax(fig, ax)

        # We are not plotting actual values, hide both axis.
        ax.axis('off')

        # Automatically show labels for small networks.
        if self.with_labels is None and len(self.data) < 10:
            self.with_labels = True
        
        # Increase node size to fit labels.
        if self.node_size is None:
            if self.with_labels:
                self.node_size = 300
            else:
                self.node_size = 20

        nx.draw_networkx_edges(graph, pos, ax=ax, arrows=False)

        if self.directed:
            # Networkx default "directed" visualization just draws a thicker stub at the end.
            # This code adds actual arrow heads, taking care not to overlap the nodes themselves.
            for start, end in self.data:
                if start == end:
                    continue
                start_x, start_y = pos[start]
                end_x, end_y = pos[end]
                angle = math.atan2(end_y-start_y, end_x-start_x)
                distance = math.sqrt((end_x - start_x)**2 + (end_y - start_y)**2)
                end_pos = (end_x - 0.1 * distance * math.cos(angle), end_y - 0.1 * distance * math.sin(angle))
                ax.add_patch(FancyArrowPatch(posA=(start_x, start_y), posB=end_pos,
                                    color='k', arrowstyle=self.arrowstyle,
                                    mutation_scale=30, connectionstyle="arc3"))

        nx.draw_networkx_nodes(graph, pos, node_size=self.node_size, ax=ax, node_color=self.node_color, cmap=self.cmap)

        if self.with_labels:
            if max(len(str(l)) for l in pos) <= 2:
                nx.draw_networkx_labels(graph, pos, fontsize=self.fontsize, ax=ax)
            else:
                # Large labels don't look because they don't fit. In that case
                # we draw them outside the node, slightly above, with a white
                # box behind.
                for label, (x, y) in pos.items():
                    ax.text(x, y+self.fontsize, label, ha='center', fontsize=self.fontsize, bbox={'color': 'white', 'alpha': 1})

        if fig:
            # Resize plot to fill available space.
            fig.tight_layout()