def circos_plotting(self, G): # Iterate over all the nodes, including the metadata for n, d in G.nodes(data=True): # Calculate the degree of each node: G.node[n]['degree'] G.node[n]['degree'] = nx.degree(G, n) # Create the CircosPlot object: c c = CircosPlot(graph=G, node_order='degree') # Draw the CircosPlot object to the screen c.draw() plt.show()
def maximal_clique(self, G): # Find the author(s) that are part of the largest maximal clique: largest_clique largest_clique = sorted(nx.find_cliques(G), key=lambda x: len(x))[-1] # Create the subgraph of the largest_clique: G_lc G_lc = G.subgraph(largest_clique) # Create the CircosPlot object: c c = CircosPlot(G_lc) # Draw the CircosPlot to the screen c.draw() plt.show()
def test_edge_widths(): # add weight as attribute and fill with random numbers edges = G.edges() for u, v in edges: G[u][v]["weight"] = random() # also extract list for testing weights = [G[u][v]["weight"] for u, v in edges] # add weights as proptery c = CircosPlot(G, edge_width="weight") assert c.edge_widths == weights a = ArcPlot(G, edge_width="weight") assert a.edge_widths == weights # add weights as list c = CircosPlot(G, edge_width=weights) assert c.edge_widths == weights a = ArcPlot(G, edge_width=weights) assert a.edge_widths == weights
def test_edge_color(): # add color as attribute and fill with random numbers edges = G.edges() for u, v in edges: G[u][v]["type"] = "a" if random() < 0.5 else "b" # also extract list for testing types = [G[u][v]["type"] for u, v in edges] # add color as property c = CircosPlot(G, edge_color="type") assert corresponding_lists(c.edge_colors, types) a = ArcPlot(G, edge_color="type") assert corresponding_lists(a.edge_colors, types)
def plot_cc_subgraph(G): """Plot all connected component subgraphs.""" c = CircosPlot(G, node_color="subgraph", node_order="subgraph") c.draw()
a.draw() plt.show() # Import necessary modules from nxviz import CircosPlot import matplotlib.pyplot as plt # Iterate over all the nodes, including the metadata for n, d in G.nodes(data=True): # Calculate the degree of each node: G.node[n]['degree'] G.node[n]["degree"] = nx.degree(G, n) # Create the CircosPlot object: c c = CircosPlot(graph=G, node_order="degree", node_grouping="grouping", node_color="grouping") # Draw the CircosPlot object to the screen c.draw() plt.show() # Calculate the maximal cliques in G: cliques cliques = nx.find_cliques(G) # Count and print the number of maximal cliques in G print(len(list(cliques))) # Import necessary modules import networkx as nx from nxviz import CircosPlot
""" Shows how to rotate node labels. This increaes legibility for longer labels. """ import matplotlib.pyplot as plt import networkx as nx from nxviz import CircosPlot G = nx.barbell_graph(m1=5, m2=3) # let's give the nodes some longer labels G = nx.relabel_nodes(G, {i: "long name #" + str(i) for i in range(len(G))}) # try it `node_label_layout=False` to see how the long names overlap each other c = CircosPlot(G, node_labels=True, node_label_layout='numbers') c.node_colors = ['skyblue' for node_color in c.node_colors] c.draw() # the rotated labels take up more space, so we will have to increase the # padding a bit. 15% on all sides works well here. plt.tight_layout(rect=(0.15, 0.15, 0.85, 0.85)) plt.show()
def plot_graph_circos(graph, sc_threshold=0.07): # Some parts of the code from: # https://github.com/multinetlab-amsterdam/network_TDA_tutorial G = graph.copy() # remove weak connections for edge in nx.get_edge_attributes(G, 'weight').items(): if edge[1] < sc_threshold: G.remove_edge(edge[0][0], edge[0][1]) atlas = atlases.AutomatedAnatomicalParcellation2() atlas = aal2_atlas_add_cortical_regions(atlas) G = nx.relabel_nodes(G, lambda x: atlas.names('cortex')[x]) sublist = {} order = {} n = 0 for group in list(CORTICAL_REGIONS.keys()): for i in atlas.names(group=group): sublist[i] = group if i[-1] == 'L': order[i] = n else: order[i] = n + 1 n += 2 nx.set_node_attributes(G, sublist, 'cortical_region') nx.set_node_attributes(G, order, 'node_order') # https://nxviz.readthedocs.io/en/latest/modules.html circ = CircosPlot(G, figsize=(15, 15), node_labels=True, node_label_layout='rotation', edge_color='weight', edge_width='weight', fontsize=10, node_order='node_order', nodeprops={"radius": 1}, group_label_offset=5, node_color='cortical_region', group_legend=True) circ.draw() circ.sm.colorbar.remove() labels_networks = sorted( list( set([ list(circ.graph.nodes.values())[n][circ.node_color] for n in np.arange(len(circ.nodes)) ]))) plt.legend(handles=circ.legend_handles, title="Subnetwork", ncol=2, borderpad=1, shadow=True, fancybox=True, bbox_to_anchor=(0.8, 1.05), loc='upper left', fontsize=10, labels=labels_networks) plt.tight_layout() return circ
def test_circos_plot(): c = CircosPlot(G) # noqa: F841 diff = diff_plots(c, "circos.png", baseline_dir, result_dir) assert diff is None
cen_clos = nx.closeness_centrality(H) cc = nx.clustering(H) for v in H.nodes(): node = H.nodes[v] node['degree'] = deg_cen[v] node['betweeness'] = cen_btw[v] node['eigenvector'] = cen_ei[v] node['closeness'] = cen_clos[v] node['clustering'] = float(cc[v]) # --------------- # --- PLOTTING --- indexes = ['degree', 'betweeness', 'eigenvector', 'closeness', 'clustering'] for i in indexes: current = CircosPlot(H, title=i, node_color=i, node_order=i, node_labels=True) current.draw() plt.title(i.capitalize()) plt.suptitle(i.capitalize()) plt.savefig(f"output/{i}.png") # ---------------
filename = 'C:\\Users\\Jose\\Desktop\\PythonDataScience\\NetworkAnalysis\\ego-twitter.p' infile = open(filename, 'rb') myfile = pickle.load(infile) infile.close() # G = nx.path_graph(50) # nx.write_gpickle(G, filename) G = nx.read_gpickle(filename) # G = nx.read_gpickle(filename) print(type(G)) # Create Ghe CircosPlot object: c c = CircosPlot(G) # Draw c to the screen c.draw() plt.show() # Create the un-customized ArcPlot object: a a = ArcPlot(G) # Draw a to the screen a.draw() # Display the plot plt.show() # Create the customized ArcPlot object: a2
if d['date'] < datetime(2004, 5, 16)]) ''' INSTRUCTIONS * Compute degree centrality scores of each node using the bipartite module degree centralities, but based on the degree centrality in the original graph. * Use the nx.bipartite.degree_centrality() function for this, with the arguments G and nodes=forum_nodes. * Create a new CircosPlot object with nodes colored and grouped (parameters node_color and node_grouping) by their partition label ('bipartite'), and ordered (parameter node_order) by their degree centrality ('dc') * Plot the CircosPlot to screen. ''' # Import necessary modules from nxviz import CircosPlot import matplotlib.pyplot as plt # Compute degree centrality scores of each node dcs = nx.bipartite.degree_centrality(G, nodes=forum_nodes) for n, d in G_sub.nodes(data=True): G_sub.node[n]['dc'] = dcs[n] # Create the CircosPlot object: c c = CircosPlot(graph=G_sub, node_color='bipartite', node_grouping='bipartite', node_order='dc') # Draw c to screen c.draw() # Display the plot plt.show()
def test_plot_size(): c = CircosPlot(G, figsize=(3, 3)) # noqa: F841
# as a directed graph: T_conv Mat = nv.MatrixPlot(G_conv) # node_order='c', node_color='C',edge_color=None) # This creates a Matplot object Mat. Mat.draw() #plt.show() plt.savefig('./figures/Matrixplot_credit_transaction.png') x = nx.adj_matrix(G_conv) print(x.todense()) ## Cercoplot from nxviz import CircosPlot Mat = CircosPlot(G, node_labels=True, node_order='Y', font_size=32, node_color='C', figsize=(8, 8), font_weight='bold') # This creates a circosplot object Mat. Mat.draw() plt.savefig('./figures/Cerco_credit_transaction.png') plt.show() ## Arcplot from nxviz import ArcPlot Mat = ArcPlot(G, node_labels=True, font_size=25, node_order='Y', node_color='C',
def test_circos_plot(): c = CircosPlot(G) # noqa: F841
test_answer(mf_count) from nxviz import MatrixPlot m = MatrixPlot(g) m.draw() plt.show() from nxviz import ArcPlot a = ArcPlot(g) a.draw() from nxviz import CircosPlot c = CircosPlot(g) c.draw() plt.show() # plt.savefig('images/seventh.png', dpi=300) #%% hiveplot #%% #%% DG = nx.DiGraph() # make a directed graph (digraph) DG.add_nodes_from(["S", "A", "B", "C", "D", "E", "T"]) # add nodes DG.add_edges_from([("S", "A"), ("S", "B"), ("S", "C"), ("A", "B"), ("A", "D"), ("B", "D"), ("B", "C"), ("B", "E"), ("C", "E"), ("D", "T"), ("E", "T")]) # specify the capacity values for the edges: nx.set_edge_attributes(
nx.draw(G_WC,pos,with_labels=True,edge_color='g',node_size =size_from_wins_wc) plt.show() !pip install nxviz # Import necessary modules to use Circos plot import matplotlib.pyplot as plt from nxviz import CircosPlot # Create the CircosPlot object - CBLOL c = CircosPlot(G_CBLOL, node_size = size_from_wins_cblol, node_labels=True, figsize = (15,15), nodeprops={"radius": 0.5}, fontsize=12 ) # Draw c to the screen c.draw() c.figure.tight_layout() # Display the plot plt.show() # Create the CircosPlot object - MSI m = CircosPlot(G_MSI, node_size = size_from_wins_msi,
"""#Grafo com nxviz""" !pip install nxviz # Import necessary modules to use Circos plot import matplotlib.pyplot as plt from nxviz import CircosPlot # create an egocentric network from ego and G egonet = nx.ego_graph(G, ego) # Create the CircosPlot object: c c = CircosPlot(egonet, node_labels=True, figsize = (15,10), nodeprops={"radius": 0.5}, #node_label_layout="rotation", #node_label_layout="numbers", fontsize=12 ) # find ego node for i,label in enumerate(c.nodes): if label == ego: ego_index = i break # Draw c to the screen c.node_colors[ego_index] = "red" c.draw() c.figure.tight_layout()
def test_circos_plot(): c = CircosPlot(G)
''' Visualizing using Circos plots Circos plots are a rational, non-cluttered way of visualizing graph data, in which nodes are ordered around the circumference in some fashion, and the edges are drawn within the circle that results, giving a beautiful as well as informative visualization about the structure of the network. In this exercise, you'll continue getting practice with the nxviz API, this time with the CircosPlot object. matplotlib.pyplot has been imported for you as plt. INSTRUCTIONS 100XP Import CircosPlot from nxviz. Plot the Twitter network T as a Circos plot without any styling. Use the CircosPlot() function to do this. Don't forget to draw it to the screen using .draw() and then display it using plt.show(). ''' # Import necessary modules import matplotlib.pyplot as plt from nxviz import CircosPlot # Create the CircosPlot object: c c = CircosPlot(T) # Draw c to the screen c.draw() # Display the plot plt.show()
100 XP Make a CircosPlot of the network, again, with GitHub users sorted by their degree, and grouped and coloured by their 'grouping' key. To do this: Iterate over all the nodes in G, including the metadata (by specifying data=True). In each iteration of the loop, calculate the degree of each node n with nx.degree() and set its 'degree' attribute. Create the CircosPlot object c by specifying three parameters in addition to the graph G: the node_order, which is 'degree', the node_grouping and the node_color, which are both 'grouping'. Draw the CircosPlot object to the screen. ''' # Import necessary modules from nxviz import CircosPlot import matplotlib.pyplot as plt # Iterate over all the nodes, including the metadata for n, d in G.nodes(data=True): # Calculate the degree of each node: G.node[n]['degree'] G.node[n]['degree'] = nx.degree(G, n) # Create the CircosPlot object: c c = CircosPlot(graph=G, node_order='degree', node_grouping='grouping', node_color='grouping') # Draw the CircosPlot object to the screen c.draw() plt.show()
G = nx.Graph() G.add_nodes_from(nodes) G.add_edges_from(edges) ''' INSTRUCTIONS * Find the author(s) that are part of the largest maximal clique, and plot the subgraph of that/one of those clique(s) using a CircosPlot. To do this: * Use the nx.find_cliques() function to calculate the maximal cliques in G. Place this within the provided sorted() function to calculate the largest maximal clique. * Create the subgraph consisting of the largest maximal clique using the .subgraph() method and largest_clique. * Create the CircosPlot object using the subgraph G_lc (without any other arguments) and plot it. ''' # Import necessary modules import networkx as nx from nxviz import CircosPlot import matplotlib.pyplot as plt # Find the author(s) that are part of the largest maximal clique: largest_clique largest_clique = sorted(nx.find_cliques(G), key=lambda x: len(x))[-1] # Create the subgraph of the largest_clique: G_lc G_lc = G.subgraph(largest_clique) # Create the CircosPlot object: c c = CircosPlot(G_lc) # Draw the CircosPlot to the screen c.draw() plt.show()
''' Visualizing using Circos plots Circos plots are a rational, non-cluttered way of visualizing graph data, in which nodes are ordered around the circumference in some fashion, and the edges are drawn within the circle that results, giving a beautiful as well as informative visualization about the structure of the network. In this exercise, you'll continue getting practice with the nxviz API, this time with the CircosPlot object. matplotlib.pyplot has been imported for you as plt. Instructions 100 XP Import CircosPlot from nxviz. Plot the Twitter network T as a Circos plot without any styling. Use the CircosPlot() function to do this. Don't forget to draw it to the screen using .draw() and then display it using plt.show(). ''' SOLUTION # Import necessary modules import matplotlib.pyplot as plt from nxviz import CircosPlot # Create the CircosPlot object: c c = CircosPlot(T) # Draw c to the screen c.draw() # Display the plot plt.show()
def test_plot_size(): c = CircosPlot(G, figsize=(3, 3)) # noqa: F841 diff = diff_plots(c, "circos33.png", baseline_dir, result_dir) assert diff is None
""" Finding cliques (II) Great work! Let's continue by finding a particular maximal clique, and then plotting that clique. INSTRUCTION ----------- Find the author(s) that are part of the largest maximal clique, and plot the subgraph of that/one of those clique(s) using a CircosPlot. To do this: Use the nx.find_cliques() function to calculate the maximal cliques in G. Place this within the provided sorted() function to calculate the largest maximal clique. Create the subgraph consisting of the largest maximal clique using the .subgraph() method and largest_clique. Create the CircosPlot object using the subgraph G_lc (without any other arguments) and plot it. """ # Import necessary modules import networkx as nx from nxviz import CircosPlot import matplotlib.pyplot as plt # Find the author(s) that are part of the largest maximal clique: largest_clique largest_clique = sorted(nx.find_cliques(G), key=lambda x: len(x))[-1] # Create the subgraph of the largest_clique: G_lc G_lc = G.subgraph(largest_clique) # Create the CircosPlot object: c c = CircosPlot(graph=G_lc) # Draw the CircosPlot to the screen c.draw() plt.show()
def circos_plot(G): """Draw a Circos Plot of the graph.""" c = CircosPlot(G, node_order="order", node_color="order") c.draw()
""" Shows how to rotate node labels. This increaes legibility for longer labels. """ from random import choice import matplotlib.pyplot as plt import networkx as nx from nxviz import CircosPlot G = nx.barbell_graph(m1=20, m2=3) for n, d in G.nodes(data=True): G.node[n]["class"] = choice(["one", "two", "three", "four", "five"]) c = CircosPlot( G, node_grouping="class", node_color="class", node_order="class", group_label_position="middle", nodeprops={"radius": 1}, node_label_layout="rotation", fontsize=12, fontfamily="fantasy", ) c.draw() plt.show()
""" Shows how to rotate node labels. This increaes legibility for longer labels. """ import matplotlib.pyplot as plt import networkx as nx from nxviz import CircosPlot G = nx.barbell_graph(m1=20, m2=3) # let's give the nodes some longer labels G = nx.relabel_nodes(G, {i: "long name " + str(i) for i in range(len(G))}) # try it `node_label_layout=False` to see how the long names overlap each other c = CircosPlot(G, node_labels=True, node_label_layout="rotation") c.draw() # the rotated labels take up more space, so we will have to increase the # padding a bit. 15% on all sides works well here. plt.tight_layout(rect=(0.15, 0.15, 0.85, 0.85)) plt.show()
import matplotlib.pyplot as plt from nxviz import CircosPlot # read data # split the data in personal into two file to create an index file named emails # previously change 'date' to DATE type in excel personal = pd.read_csv("F:/UIUC/590DV/homework5/personalemail.csv") emails = pd.read_csv("F:/UIUC/590DV/homework5/personal_sender_receiver.csv") # initialize graph G = nx.DiGraph() # add in the node attribute for d in emails.to_dict("records"): node_id = d.pop("id") G.add_node(node_id, **d) # add edges counts = personal.groupby(["sender_id", "receiver_id"])["id"].count().reset_index() for d in counts.to_dict("records"): G.add_edge(d["sender_id"], d["receiver_id"], count=d["id"]) # filtered graph nx.draw_kamada_kawai(G) # Use a Circos Plot c = CircosPlot(G, radius=10, nodecolor="blue", edgecolor="red") c.draw() plt.savefig("F:/UIUC/590DV/homework5/personal_email.png", dpi=300)
plt.show() ############################### Task 3 (CircosPlot) # Import necessary modules from nxviz import CircosPlot import matplotlib.pyplot as plt # Iterate over all the nodes, including the metadata for n, d in G.nodes(data=True): # Calculate the degree of each node: G.node[n]['degree'] G.node[n]['degree'] = nx.degree(G, n) # Create the CircosPlot object: c c = CircosPlot(G, node_order='degree', node_grouping='grouping', node_color='grouping') # Draw the CircosPlot object to the screen c.draw() plt.show() ############################## Cliques #################################### import networkx as nx G = nx.erdos_renyi_graph(n=200, p=0.15) nx.find_cliques(G) for clique in nx.find_cliques(G): print(len(clique))
""" Shows how to rotate node labels. This increaes legibility for longer labels. """ import matplotlib.pyplot as plt import networkx as nx from nxviz import CircosPlot G = nx.barbell_graph(m1=5, m2=3) # let's give the nodes some longer labels G = nx.relabel_nodes(G, {i: "long name #" + str(i) for i in range(len(G))}) # try it `node_label_layout=False` to see how the long names overlap each other c = CircosPlot(G, node_labels=True, node_label_layout="numbers") c.node_colors = ["skyblue" for node_color in c.node_colors] c.draw() # the rotated labels take up more space, so we will have to increase the # padding a bit. 15% on all sides works well here. plt.tight_layout(rect=(0.15, 0.15, 0.85, 0.85)) plt.show()