def plot_graph(args): if not isinstance(args.dataset, list): args.dataset = [args.dataset] for name in args.dataset: dataset = build_dataset_from_name(name) data = dataset[0] depth = args.depth pic_file = osp.join(args.save_dir, f'display_{name}.png') col_names = [ 'Dataset', '#nodes', '#edges', '#features', '#classes', '#labeled data' ] tab_data = [[ name, data.x.shape[0], data.edge_index.shape[1], data.x.shape[1], len(set(data.y.numpy())), sum(data.train_mask.numpy()) ]] print(tabulate(tab_data, headers=col_names, tablefmt='psql')) G = nx.Graph() G.add_edges_from([ tuple(data.edge_index[:, i].numpy()) for i in range(data.edge_index.shape[1]) ]) s = random.choice(list(G.nodes())) q = [s] node_set = set([s]) node_index = {s: 0} max_index = 1 for _ in range(depth): nq = [] for x in q: for key in G[x].keys(): if key not in node_set: nq.append(key) node_set.add(key) node_index[key] = node_index[x] + 1 if len(nq) > 0: max_index += 1 q = nq cmap = cm.rainbow(np.linspace(0.0, 1.0, max_index)) for node, index in node_index.items(): G.nodes[node]['color'] = cmap[index] G.nodes[node]['size'] = (max_index - index) * 50 fig, ax = plt.subplots() plot_network(G.subgraph(list(node_set)), node_style=use_attributes()) plt.savefig(pic_file) print(f'Sampled ego network saved to {pic_file} .')
def _call(self, dataset="cora", seed=-1, depth=3, **kwargs): if isinstance(dataset, list): dataset = dataset[0] name = dataset dataset = build_dataset_from_name(name) data = dataset[0] G = nx.Graph() edge_index = torch.stack(data.edge_index) G.add_edges_from([ tuple(edge_index[:, i].numpy()) for i in range(edge_index.shape[1]) ]) if seed == -1: seed = random.choice(list(G.nodes())) q = [seed] node_set = set([seed]) node_index = {seed: 0} max_index = 1 for _ in range(depth): nq = [] for x in q: for key in G[x].keys(): if key not in node_set: nq.append(key) node_set.add(key) node_index[key] = node_index[x] + 1 if len(nq) > 0: max_index += 1 q = nq cmap = cm.rainbow(np.linspace(0.0, 1.0, max_index)) for node, index in node_index.items(): G.nodes[node]["color"] = cmap[index] G.nodes[node]["size"] = (max_index - index) * 50 pic_file = f"{name}.png" plt.subplots() plot_network(G.subgraph(list(node_set)), node_style=use_attributes()) plt.savefig(pic_file) print(f"Sampled ego network saved to {pic_file}") return q
def drawGraph(genes_names_list, network_as_list): G = nx.MultiDiGraph() G.add_nodes_from(genes_names_list) val_map = {'ARR23': 1.0, 'CRF2': 0.5714285714285714} values = [val_map.get(node, 0.85) for node in G.nodes()] #ajout des aretes et des noeuds for i in range(len(network_as_list)): gene_source = network_as_list[i][0] gene_target = network_as_list[i][2] interaction = network_as_list[i][1] G.add_edge(gene_source, gene_target, arrowstyle=interaction) # if gene_source not in G.nodes : # if gene_target == gene_source : # G.add_node(gene_source, regulation = "auto") # else: # G.add_node(gene_source, regulation = "none") print(G.adj) pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos, node_size=1500, node_color=values) nx.draw_networkx_labels(G, pos) for edge in G.edges(data=True): if edge[2]['arrowstyle'] == "-1": arrowstyle = "-[" else: arrowstyle = "-|>" nx.draw_networkx_edges(G, pos, edgelist=[(edge[0], edge[1])], arrowstyle=arrowstyle, node_size=1900) # plt.show() plt.gca().yaxis.set_minor_formatter(NullFormatter()) plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0.25, wspace=0.35) fig = plt.gcf() art = plot_network(G, node_style=use_attributes(), edge_style=use_attributes()) art.set_picker(10) # if using Pyplot then get the figure from the plot return fig
def draw_workflow(dol, simulations): graph = nx.from_dict_of_lists(dol, create_using=None) fig, ax = plt.subplots() art = plot_network(graph, ax=ax, node_style=use_attributes(), edge_style=use_attributes(), #layout="kamada_kawai", #node_label_style = {'font_weight': 'bold', 'font_size': 15} ) art.set_picker(10) ax.set_title('workflow simulations, click on the nodes to see structure') fig.canvas.mpl_connect('pick_event', hilighter) plt.show() plt.close() return
def plotGraph(self): G = self.graph[0] largest_node = self.graph[1] G.add_edge(largest_node, largest_node) for node in G.nodes: G.nodes[node]["size"] = 200 G.nodes[node]["color"] = 'C0' G.nodes[largest_node]["size"] = 400 G.nodes[largest_node]["color"] = "red" self.app.axes.clear() self.app.selectedDocument.setText("") graph = plot_network(G, layout="spring", ax=self.app.axes, node_style=use_attributes(), edge_style=use_attributes()) graph.set_picker(10) self.app.canvas.mpl_connect('pick_event', self.app.selectNode) self.app.update_graph.emit()
def set_graph(self): """ Draws current graph on canvas """ # add dummy edge if no edges # circumvent the fact that drawing graph with no edges is not supported if self.graph.number_of_edges() == 0: for n in self.graph.nodes: self.graph.add_edge(n, n) if args.dataset == "clevr": layout = "circular" else: layout = self.g_layout self._static_ax.clear() self.art = plot_network( self.graph, layout=layout, ax=self._static_ax, #self.g_layout, "spring" node_style=use_attributes( ), # use_attributes(), #node_options, #dict(node_size=50), edge_style=use_attributes(), # ) #edge_options) # #, node_label_style={ 'font_size': '10', 'font_weight': 'bold' }) # layout=self.g_layout self.art.set_picker(10) self._static_ax.figure.canvas.draw_idle() # reset combobox for node choices and update with new object list for i in range(self.comboBox_obj2.count()): self.comboBox_obj2.removeItem(0) for obj in self.graph.nodes: if obj.split(".")[0] in objs: self.comboBox_obj2.addItem(obj)
import matplotlib.pyplot as plt import networkx as nx from networkx.algorithms.approximation.dominating_set import * #min_weighted_dominating_set from grave import plot_network network = nx.powerlaw_cluster_graph(50, 1, .2) dom_set = min_weighted_dominating_set(network) for node, node_attrs in network.nodes(data=True): node_attrs['is_dominator'] = True if node in dom_set else False def color_dominators(node_attrs): if node_attrs.get('is_dominator', False): return {'color': 'red'} else: return {'color': 'black'} fig, ax = plt.subplots() plot_network(network, node_style=color_dominators) plt.show()
import matplotlib.pyplot as plt from grave import plot_network, use_attributes toy_network = nx.barbell_graph(10, 14) toy_centrality = closeness_centrality(toy_network) max_centrality = max(toy_centrality.values()) for u, v, edge_attributes in toy_network.edges.data(): c = (toy_centrality[u] + toy_centrality[v]) / 2 color_idx = (c / max_centrality) cmap = plt.get_cmap() edge_attributes['color'] = cmap(color_idx) edge_attributes['width'] = 2 for node, node_attributes in toy_network.nodes.data(): node_attributes['size'] = (1 - (toy_centrality[node] / max_centrality) + .1) * 100 def edge_style(edge_attributes): return {'linewidth': edge_attributes.get('weight', 1)} fig, ax = plt.subplots() plot_network(toy_network, layout='spring', node_style=use_attributes(), edge_style=use_attributes('color')) plt.show()
""" Grave Documentation ------------------- """ import networkx as nx from networkx.algorithms.approximation.dominating_set import min_weighted_dominating_set import matplotlib.pyplot as plt from grave import plot_network, use_attributes toy_network = nx.barbell_graph(10, 14) dom_set = min_weighted_dominating_set(toy_network) for node, node_attrs in toy_network.nodes(data=True): if node in dom_set: node_attrs['color'] = 'red' else: node_attrs['color'] = 'black' node_attrs['size'] = 50 fig, ax = plt.subplots() plot_network(toy_network, node_style=use_attributes()) plt.show()
def test_smoke_graph(): graph = nx.barbell_graph(10, 14) plot_network(graph)
def __init__( self, graph, layout="spectral", node_style=None, edge_style=None, node_label_style=None, edge_label_style=None, ax=None, force_draw=False, ): """ Parameters ---------- graph : nx.Graph The graph to be plotted layout : string or callable, optional, default: "spectral" Specifies the type of layout to use for plotting. It must be one of "spring", "circular", "random", "kamada_kawai", "shell", "spectral", or a callable. node_style : dict or callable, optional The style parameters for nodes, if callable must return a dict edge_style : dict or callable, optional The style parameters for edges, if callable must return a dict node_label_style : dict or callable, optional The style parameters for node labels, if callable must return a dict edge_label_style : dict or callable, optional The style parameters for edge labels, if callable must return a dict ax : matplotlib axis object, optional The axis to plot on. If not provided produce fig and ax internally. force_draw : bool, optional If True force drawing every time graph is updated, else only draw when idle. Defaults to False """ self.force_draw = force_draw if edge_label_style is None: edge_label_style = {} if node_label_style is None: node_label_style = {} if edge_style is None: edge_style = {} if node_style is None: node_style = {} self.node_style = node_style self.edge_style = edge_style self.node_label_style = node_label_style self.edge_label_style = edge_label_style self.layout = layout self.graph = graph if not ax: fig, ax = plt.subplots() self.ax = ax self.art = plot_network( self.graph, node_style=self.node_style, edge_style=self.edge_style, node_label_style=self.node_label_style, edge_label_style=self.edge_label_style, layout=self.layout, ax=self.ax, ) self.update()
# clear any non-default color on nodes for node, attributes in graph.nodes.data(): attributes.pop('color', None) for u, v, attributes in graph.edges.data(): attributes.pop('width', None) for node in event.nodes: graph.nodes[node]['color'] = 'C1' for edge_attribute in graph[node].values(): edge_attribute['width'] = 3 # update the screen event.artist.stale = True event.artist.figure.canvas.draw_idle() graph = nx.barbell_graph(10, 14) fig, ax = plt.subplots() art = plot_network(graph, ax=ax, node_style=use_attributes(), edge_style=use_attributes()) art.set_picker(10) ax.set_title('Click on the nodes!') fig.canvas.mpl_connect('pick_event', hilighter) plt.show()
# create attribute for label nx.set_edge_attributes(H, {e: G.edges[e]['weight'] for e in H.edges}, 'label') # create stylers def transfer_G_layout(network): return {n: G.position[n] for n in network} def elabel_base_style(attr): return {'font_size': 4, 'font_weight': 'bold', 'font_family': 'sans-serif', 'font_color': 'b', 'rotate': True, # TODO: make rotation less granular } elabel_style = grave.style_merger(grave.use_attributes('label'), elabel_base_style) grave.plot_network(H, transfer_G_layout, node_style=dict(node_size=20), edge_label_style=elabel_style, node_label_style={'font_weight': 'bold'}) # scale the axes equally plt.xlim(-5000, 500) plt.ylim(-2000, 3500) plt.show()
""" A dead simple network --------------------- The simplest way to plot a graph ever. And yet it looks cool! """ import networkx as nx import matplotlib.pyplot as plt from grave import plot_network # Generate a networkx graph graph = nx.powerlaw_cluster_graph(50, 1, .2) # Plot it plot_network(graph)
def test_graph_no_edges(): graph = nx.Graph() graph.add_node(0) plot_network(graph)
""" A simple network ---------------- Test """ import networkx as nx import matplotlib.pyplot as plt from grave import plot_network graph = nx.barbell_graph(10, 14) nx.set_node_attributes(graph, dict(graph.degree()), 'degree') fig, ax = plt.subplots() plot_network(graph, ax=ax) plt.show()
return {'color': 'b', 'size': 20 * deg, 'shape': shape} def font_styler(attributes): return {'font_size': 8, 'font_weight': .5, 'font_color': 'k'} def tiny_font_styler(attributes): return {'font_size': 4, 'font_weight': .5, 'font_color': 'r'} def pathological_edge_style(edge_attrs): return {'color': random.choice(['r', (0, 1, 0, .5), 'xkcd:ocean'])} network = nx.grid_2d_graph(4, 6) nx.set_node_attributes(network, dict(network.degree()), 'degree') fig, ax = plt.subplots() plot_network(network, ax=ax, layout=lambda G: {node: node for node in G}, node_style=degree_colorer, edge_style=pathological_edge_style, node_label_style=font_styler, edge_label_style=tiny_font_styler) plt.show()
""" Using another style =================== In this example, we show how to use another default Matplotlib style. """ import networkx as nx import matplotlib.pyplot as plt from grave import plot_network network = nx.binomial_graph(50, .05) fig, ax_mat = plt.subplots(ncols=2) plot_network(network, ax=ax_mat[0]) ax_mat[0].set_axis_on() with plt.style.context(('ggplot')): plot_network(network, ax=ax_mat[1]) ax_mat[1].set_axis_on() for ax in ax_mat: ax.set_axis_on() ax.tick_params(which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) plt.show()
Test """ import networkx as nx import matplotlib.pyplot as plt import random from grave import plot_network graph = nx.barbell_graph(10, 14) nx.set_node_attributes(graph, dict(graph.degree()), 'degree') def degree_colorer(node_attributes): deg = node_attributes['degree'] shape = random.choice(['s', 'o', '^', 'v', '8']) if deg > 5: return {'color': 'r', 'size': 20 * deg, 'shape': shape} return {'color': 'b', 'size': 20 * deg, 'shape': shape} def pathological_edge_style(edge_attrs): return {'color': random.choice(['r', (0, 1, 0, .5), 'xkcd:ocean'])} fig, ax = plt.subplots() plot_network(graph, ax=ax, node_style=degree_colorer, edge_style=pathological_edge_style) plt.show()