I want to create a graph and draw it, so far so good, but the problem is that i want to draw more information on each node.
I saw i can save attributes to nodes\edges, but how do i draw the attributes?
i'm using PyGraphviz witch uses Graphviz.
An example would be
import pygraphviz as pgv
from pygraphviz import *
G=pgv.AGraph()
ndlist = [1,2,3]
for node in ndlist:
label = "Label #" + str(node)
G.add_node(node, label=label)
G.layout()
G.draw('example.png', format='png')
but make sure you explicitly add the attribute label for extra information to show as Martin mentioned https://stackoverflow.com/a/15456323/1601580.
You can only add supported attributes to nodes and edges. These attributes have specific meaning to GrpahViz.
To show extra information on edges or nodes, use the label attribute.
If you already have a graph with some attribute you want to label you can use this:
def draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name, path2file=None):
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# https://stackoverflow.com/questions/15345192/draw-more-information-on-graph-nodes-using-pygraphviz
if path2file is None:
path2file = './example.png'
path2file = Path(path2file).expanduser()
g = nx.nx_agraph.to_agraph(g)
# to label in pygrapviz make sure to have the AGraph obj have the label attribute set on the nodes
g = str(g)
g = g.replace(attribute_name, 'label') # it only
print(g)
g = pgv.AGraph(g)
g.layout()
g.draw(path2file)
# https://stackoverflow.com/questions/20597088/display-a-png-image-from-python-on-mint-15-linux
img = mpimg.imread(path2file)
plt.imshow(img)
plt.show()
# remove file https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
path2file.unlink()
# -- tests
def test_draw():
# import pylab
import networkx as nx
g = nx.Graph()
g.add_node('Golf', size='small')
g.add_node('Hummer', size='huge')
g.add_node('Soccer', size='huge')
g.add_edge('Golf', 'Hummer')
draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name='size')
if __name__ == '__main__':
test_draw()
result:
in particular note that the two huge's did not become a self loop and they are TWO different nodes (e.g. two sports can be huge but they are not the same sport/entity).
related but plotting with nx: Plotting networkx graph with node labels defaulting to node name
Related
I'm new to Python. Please help me solve the problem with graph construction. I have a database with the attribute "Source", "Interlocutor" and "Frequency".
An example of three lines:
I need to build a graph based on the Source-Interlocutor, but the frequency is also taken into account.
Like this:
My code:
dic_values={Source:[24120.0,24120.0,24120.0], Interlocutor:[34,34,34],Frequency:[446625000, 442475000, 445300000]
session_graph=pd.DataFrame(dic_values)
friquency=session_graph['Frequency'].unique()
plt.figure(figsize=(10,10))
for i in range(len(friquency)):
df_friq=session_subset[session_subset['Frequency']==friquency[i]]
G_frique=nx.from_pandas_edgelist(df_friq,source='Source',target='Interlocutor')
pos = nx.spring_layout(G_frique)
nx.draw_networkx_nodes(G_frique, pos, cmap=plt.get_cmap('jet'), node_size = 20)
nx.draw_networkx_edges(G_frique, pos, arrows=True)
nx.draw_networkx_labels(G_frique, pos)
plt.show()
And I have like this:
Your problem requires a MultiGraph
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import pydot
from IPython.display import Image
dic_values = {"Source":[24120.0,24120.0,24120.0], "Interlocutor":[34,34,34],
"Frequency":[446625000, 442475000, 445300000]}
session_graph = pd.DataFrame(dic_values)
sources = session_graph['Source'].unique()
targets = session_graph['Interlocutor'].unique()
#create a Multigraph and add the unique nodes
G = nx.MultiDiGraph()
for n in [sources, targets]:
G.add_node(n[0])
#Add edges, multiple connections between the same set of nodes okay.
# Handled by enum in Multigraph
#Itertuples() is a faster way to iterate through a Pandas dataframe. Adding one edge per row
for row in session_graph.itertuples():
#print(row[1], row[2], row[3])
G.add_edge(row[1], row[2], label=row[3])
#Now, render it to a file...
p=nx.drawing.nx_pydot.to_pydot(G)
p.write_png('multi.png')
Image(filename='multi.png') #optional
This will produce the following:
Please note that node layouts are trickier when you use Graphviz/Pydot.
For example check this SO answer.. I hope this helps you move forward. And welcome to SO.
I'm using the Louvain Algorithm below for community detection using graphs that I insert manually.
I have 2 problems here. The first one is about the color of the nodes. The color of each community of nodes, as you see below, is a bit dark or white and it is not clear as which are the exact communities.
So, which is the way to draw each community of nodes into brighter colors?
And my last question, any ideas to save the results into a new .txt after the community detection is done?
partition = community.best_partition(G)
values = [partition.get(node) for node in G.nodes()]
#drawing
size = float(len(set(partition.values())))
posi = nx.spring_layout(G)
count = 0
for com in set(partition.values()):
count = count + 1.
list_nodes = [nodes for nodes in partition.keys()
if partition[nodes] == com]
nx.draw_networkx_nodes(G, posi, list_nodes, node_size = 25, node_color=str(count/size))
#nx.draw_spring(G, cmap = plt.get_cmap('hsv'), node_color = values, node_size=30, with_labels=False)
nx.draw_networkx_edges(G, posi, alpha=0.5)
plt.show()
You can use the cmap parameter of draw_networkx_nodes, which allows you to specify any matplotlib.colormap. See here or here1 for example.
Minimal working colouring example:
import networkx as nx
import matplotlib.pylab as pl
graph = nx.karate_club_graph()
colors = []
for node in graph:
if graph.nodes[node]["club"] == "Mr. Hi":
colors.append(0)
else:
colors.append(1)
colors[0] = -1
colors[-1] = 2
nx.draw_networkx(graph, node_color=colors, vmin=min(colors), vmax=max(colors), cmap=pl.get_cmap("viridis"))
pl.axis("off")
pl.show()
For the saving of your graph, you can either choose a suitable graph format, such as GML. Then you first need to add the partition as node attribute to your graph:
for node in partition:
G.nodes[node]["cluster"] = partition[node]
# save file
nx.write_gml(G, "path_to_save_file")
# load file
saved_graph = nx.read_gml("path_to_save_file")
and afterwards save the graph together with the partition. Alternatively, you can only save the retrieved partition as json or (unsafe) via pickle.
In a Graph G i have a set of nodes. Some of them have a Attribute Type which can be MASTER or DOC. Others do not have the a Type define:
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G=nx.Graph()
[...]
>>> G.node['ART1']
{'Type': 'MASTER'}
>>> G.node['ZG1']
{'Type': 'DOC'}
>>> G.node['MG1']
{}
Afterwards I plot the Graph using
>>> nx.draw(G,with_labels = True)
>>> plt.show()
Now i get a graph with red Circles. How can I get e.g.
blue cylces for ART
red squares for DOC
purple cylces for everything undefined
in my plot?
There are various ways to select nodes based on their attributes. Here is how to do it with get_node_attributes and a list comprehension to take the subset. The drawing functions then accept a nodelist argument.
It should be easy enough to extend to a broader set of conditions or modify the appearance of each subset as suits your needs based on this approach
import networkx as nx
# define a graph, some nodes with a "Type" attribute, some without.
G = nx.Graph()
G.add_nodes_from([1,2,3], Type='MASTER')
G.add_nodes_from([4,5], Type='DOC')
G.add_nodes_from([6])
# extract nodes with specific setting of the attribute
master_nodes = [n for (n,ty) in \
nx.get_node_attributes(G,'Type').iteritems() if ty == 'MASTER']
doc_nodes = [n for (n,ty) in \
nx.get_node_attributes(G,'Type').iteritems() if ty == 'DOC']
# and find all the remaining nodes.
other_nodes = list(set(G.nodes()) - set(master_nodes) - set(doc_nodes))
# now draw them in subsets using the `nodelist` arg
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, nodelist=master_nodes, \
node_color='red', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=doc_nodes, \
node_color='blue', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=other_nodes, \
node_color='purple', node_shape='s')
I'm using NetworkX in python. Given any undirected and unweighted graph, I want to loop through all the nodes. With each node, I want to add a random edge and/or delete an existing random edge for that node with probability p. Is there a simple way to do this? Thanks a lot!
Create a new random edge in networkx
Let's set up a test graph:
import networkx as nx
import random
import matplotlib.pyplot as plt
graph = nx.Graph()
graph.add_edges_from([(1,3), (3,5), (2,4)])
nx.draw(graph, with_labels=True)
plt.show()
Now we can pick a random edge from a list of non-edge from the graph. It is not totally clear yet what is the probability you mentioned. Since you add a comment stating that you want to use random.choice I'll stick to that.
def random_edge(graph, del_orig=True):
'''
Create a new random edge and delete one of its current edge if del_orig is True.
:param graph: networkx graph
:param del_orig: bool
:return: networkx graph
'''
edges = list(graph.edges)
nonedges = list(nx.non_edges(graph))
# random edge choice
chosen_edge = random.choice(edges)
chosen_nonedge = random.choice([x for x in nonedges if chosen_edge[0] == x[0]])
if del_orig:
# delete chosen edge
graph.remove_edge(chosen_edge[0], chosen_edge[1])
# add new edge
graph.add_edge(chosen_nonedge[0], chosen_nonedge[1])
return graph
Usage exemple:
new_graph = random_edge(graph, del_orig=True)
nx.draw(new_graph, with_labels=True)
plt.show()
We can still add a probability distribution over the edges in random.choiceif you need to (using numpy.random.choice() for instance).
Given a node i, To add edges without duplication you need to know (1) what edges from i already exist and then compute (2) the set of candidate edges that don't exist from i. For removals, you already defined a method in the comment - which is based simply on (1).
Here is a function that will provide one round of randomised addition and removal, based on list comprehensions
def add_and_remove_edges(G, p_new_connection, p_remove_connection):
'''
for each node,
add a new connection to random other node, with prob p_new_connection,
remove a connection, with prob p_remove_connection
operates on G in-place
'''
new_edges = []
rem_edges = []
for node in G.nodes():
# find the other nodes this one is connected to
connected = [to for (fr, to) in G.edges(node)]
# and find the remainder of nodes, which are candidates for new edges
unconnected = [n for n in G.nodes() if not n in connected]
# probabilistically add a random edge
if len(unconnected): # only try if new edge is possible
if random.random() < p_new_connection:
new = random.choice(unconnected)
G.add_edge(node, new)
print "\tnew edge:\t {} -- {}".format(node, new)
new_edges.append( (node, new) )
# book-keeping, in case both add and remove done in same cycle
unconnected.remove(new)
connected.append(new)
# probabilistically remove a random edge
if len(connected): # only try if an edge exists to remove
if random.random() < p_remove_connection:
remove = random.choice(connected)
G.remove_edge(node, remove)
print "\tedge removed:\t {} -- {}".format(node, remove)
rem_edges.append( (node, remove) )
# book-keeping, in case lists are important later?
connected.remove(remove)
unconnected.append(remove)
return rem_edges, new_edges
To see this function in action:
import networkx as nx
import random
import matplotlib.pyplot as plt
p_new_connection = 0.1
p_remove_connection = 0.1
G = nx.karate_club_graph() # sample graph (undirected, unweighted)
# show original
plt.figure(1); plt.clf()
fig, ax = plt.subplots(2,1, num=1, sharex=True, sharey=True)
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, ax=ax[0])
# now apply one round of changes
rem_edges, new_edges = add_and_remove_edges(G, p_new_connection, p_remove_connection)
# and draw new version and highlight changes
nx.draw_networkx(G, pos=pos, ax=ax[1])
nx.draw_networkx_edges(G, pos=pos, ax=ax[1], edgelist=new_edges,
edge_color='b', width=4)
# note: to highlight edges that were removed, add them back in;
# This is obviously just for display!
G.add_edges_from(rem_edges)
nx.draw_networkx_edges(G, pos=pos, ax=ax[1], edgelist=rem_edges,
edge_color='r', style='dashed', width=4)
G.remove_edges_from(rem_edges)
plt.show()
And you should see something like this.
Note that you could also do something similar with the adjacency matrix,
A = nx.adjacency_matrix(G).todense() (it's a numpy matrix so operations like A[i,:].nonzero() would be relevant). This might be more efficient if you have extremely large networks.
I'm trying to represent some numbers as edges of a graph with connected components. For this, I've been using python's networkX module.
My graph is G, and has nodes and edges initialised as follows:
G = nx.Graph()
for (x,y) in my_set:
G.add_edge(x,y)
print G.nodes() #This prints all the nodes
print G.edges() #Prints all the edges as tuples
adj_matrix = nx.to_numpy_matrix(G)
Once I add the following line,
pos = nx.spring_layout(adj_matrix)
I get the abovementioned error.
If it might be useful, all the nodes are numbered in 9-15 digits. There are 412 nodes and 422 edges.
Detailed error:
File "pyjson.py", line 89, in <module>
mainevent()
File "pyjson.py", line 60, in mainevent
pos = nx.spring_layout(adj_matrix)
File "/usr/local/lib/python2.7/dist-packages/networkx/drawing/layout.py", line 244, in fruchterman_reingold_layout
A=nx.to_numpy_matrix(G,weight=weight)
File "/usr/local/lib/python2.7/dist-packages/networkx/convert_matrix.py", line 128, in to_numpy_matrix
nodelist = G.nodes()
AttributeError: 'matrix' object has no attribute 'nodes'
Edit: Solved below. Useful information: pos creates a dict with coordinates for each node. Doing nx.draw(G,pos) creates a pylab figure. But it doesn't display it, because pylab doesn't display automatically.
(some of this answer addresses some things in your comments. Can you add those to your question so that later users get some more context)
pos creates a dict with coordinates for each node. Doing nx.draw(G,pos) creates a pylab figure. But it doesn't display it, because pylab doesn't display automatically.
import networkx as nx
import pylab as py
G = nx.Graph()
for (x,y) in my_set:
G.add_edge(x,y)
print G.nodes() #This prints all the nodes
print G.edges() #Prints all the edges as tuples
pos = nx.spring_layout(G)
nx.draw(G,pos)
py.show() # or py.savefig('graph.pdf') if you want to create a pdf,
# similarly for png or other file types
The final py.show() will display it. py.savefig('filename.extension') will save as any of a number of filetypes based on what you use for extension.
spring_layout takes a network graph as it's first param and not a numpy array. What it returns are the positions of the nodes according to the Fruchterman-Reingold force-directed algorithm.
So you need to pass this to draw example:
import networkx as nx
%matplotlib inline
G=nx.lollipop_graph(14, 3)
nx.draw(G,nx.spring_layout(G))
yields: