python build graph with notes - python

I want to build a directed graph and subscribe edges.
import os
import scipy as sc
import pylab
import networkx
import matplotlib.pyplot as plt
from networkx import *
from numpy import *
G=networkx.DiGraph()
R=[('S0','S1'),('S1','S2'),('S1','S7'),('S2','S3'),('S2','S6'),('S3','S4'),('S3','S6'),('S4','S5'),('S5','S6'),('S6','S7'),('S7','S8'),('S7','S5'),('S8','Sk') ]
G.add_edges_from([ (2,3,) ])
G.add_edges_from(R)
networkx.draw_circular(G)
plt.show()
plt.savefig("path.png");
Now I have done this. I built a graph, but I cannot think up how to subscribe edges. For example I want to mark S0 and S1 edge like "565", etc. It will make it more visual and demostrative.
Thanks in advance!

Instead of layouting and drawing in one single step (networkx.draw_circular(G)), you can layout and draw nodes, edges, node labels and edge labels separately. Here's a small example:
import networkx as nx
import matplotlib.pyplot as plt
G=nx.DiGraph()
R=[('S0','S1'),('S1','S2'),('S1','S7'),('S0','S7')]
G.add_edges_from(R)
# Calculate layout and get all positions
pos = nx.circular_layout(G)
# Draw everything
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos,
{
('S0', 'S1'): 'edge1',
('S1', 'S2'): 'edge2',
('S1', 'S7'): 'edge3',
('S0', 'S7'): 'edge4'
}
)
plt.axis('off')
plt.savefig("path.png");
plt.show()
For more information about what parameters can be passed to the different drawing functions, check the documentation.

You can draw nodes and egdes selectively with:
# nodes
networkx.draw_networkx_nodes(graph, pos, nodelist=[list of the nodes])
# edges
networkx.draw_networkx_edges(graph, pos, edgelist=[list of edges])
There are more options at http://networkx.lanl.gov/reference/drawing.html#module-networkx.drawing.nx_pylab

well, I wanted to do this:
and I did it. i.e. I wanted to mark edges. It seems simple, but it wasn't so. Really.
full image is here http://s019.radikal.ru/i603/1204/2a/921bc6badfae.png
import os
import scipy as sc
import pylab
import networkx
import matplotlib.pyplot as plt
from networkx import *
from numpy import *
G=networkx.DiGraph()
R=[('S0','S1'),('S1','S2'),('S1','S7'),('S2','S3'),('S2','S6'),('S3','S4'),('S3','S6'),('S4','S5'),('S5','S6'),('S6','S7'),('S7','S8'),('S7','S5'),('S8','Sk') ]
G.add_edges_from(R)
label={R[1]:'a',R[2]:'b',R[3]:'c'}
networkx.draw_networkx_edge_labels(G,pos=networkx.graphviz_layout(G),edge_labels=label)
networkx.draw_graphviz(G)
plt.show()
plt.savefig("path.png");

Related

Bipartite graph in NetworkX for LARGE amount of nodes

I am trying to create bipartite of certain nodes, for small numbers it looks perfectly fine:
Image for around 30 nodes
Unfortunately, this isn't the case for more nodes like this one:
Image for more nodes
My code for determining the position of each node looks something like this:
pos = {}
pos[SOURCE_STRING] = (0, width/2)
row = 0
for arr in left_side.keys():
pos[str(arr).replace(" ","")]=(NODE_SIZE, row)
row += NODE_SIZE
row = 0
for arr in right_side.keys():
pos[str(arr).replace(" ","")]=(2*NODE_SIZE,row)
row += NODE_SIZE
pos[SINK_STRING] = (3*NODE_SIZE, width/2)
return pos
And then I feed it to the DiGraph class:
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges, len=1)
nx.draw(G, pos=pos ,node_shape = "s", with_labels = True,node_size=NODE_SIZE)
This doesn't make much sense since they should be in the same distance from each other since NODE_SIZE is constant it doesn't change for the rest of the program.
Following this thread:
Bipartite graph in NetworkX
Didn't help me either.
Can something be done about this?
Edit(Following Paul Brodersen Advice using netGraph:
Used this documentation: netgraph doc
And still got somewhat same results, such as:
netgraph try
Using edges and different positions, also played with node size, with no success.
Code:
netgraph.Graph(edges, node_layout='bipartite', node_labels=True)
plt.show()
In your netgraph call, you are not changing the node size.
My suggestion with 30 nodes:
import numpy as np
import matplotlib.pyplot as plt
from netgraph import Graph
edges = np.vstack([np.random.randint(0, 15, 60),
np.random.randint(16, 30, 60)]).T
Graph(edges, node_layout='bipartite', node_size=0.5, node_labels=True, node_label_offset=0.1, edge_width=0.1)
plt.show()
With 100 nodes:
import numpy as np
import matplotlib.pyplot as plt
from netgraph import Graph
edges = np.vstack([np.random.randint(0, 50, 200),
np.random.randint(51, 100, 200)]).T
Graph(edges, node_layout='bipartite', node_size=0.5, node_labels=True, node_label_offset=0.1, edge_width=0.1)
plt.show()

Python networkx - How to draw graph with labels

from graphviz import *
import networkx as nx
from networkx import *
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_edge(1,2)
myLabels = {1: 'node1', 2: 'node2'}
nx.set_node_attributes(G, myLabels, 'label')
nx.draw(G,with_labels=True)
So current I use the latest networkx. When I use nx.draw(G, with_values=True), it uses the vertex indexes instead of labels.
How can I fix this? Thank you.
Change this command: nx.draw(G,with_labels=True) to nx.draw(G,with_labels=True, labels = myLabels)

How can I draw a network?

I want to draw a network like this:
This is my code:
import matplotlib
matplotlib.use('TkAgg')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from itertools import product
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
from pymnet import*
import matplotlib.colors as mcolors
mst_pearson=mst_tree(pearson)
mst_kendall=mst_tree(kendall)
mst_tail=mst_tree(tail)
nx.draw(mst_pearson,pos=nx.spring_layout(mst_pearson))
plt.show()
mst_pearson is my own function to generate the minimum spanning tree of the graph,but my graph likes this although I set the layout:
How could I change the layout of nodes and the edges? Thanks in advance.
With the function
nx.draw_networkx_nodes(G, pos, [...])
you can use the pos argument in order to set a specific layout.
For example I have this snippet code in order to do that inside a custom function
def custom_draw_graph_function(graph_layout='shell'):
# these are different layouts for the network you may try
if(graph_layout == 'spring'):
graph_pos=nx.spring_layout(G)
elif(graph_layout == 'spectral'):
graph_pos=nx.spectral_layout(G)
elif(graph_layout == 'circular'):
graph_pos = nx.circular_layout(G)
elif(graph_layout == 'fruchterman'):
graph_pos = nx.fruchterman_reingold_layout(G)
elif(graph_layout == 'shell'):
graph_pos = nx.shell_layout(G)
else:
graph_pos=nx.random_layout(G)
# DRAW GRAPH
# Nodes
nx.draw_networkx_nodes(G,graph_pos,[...])
[...]

Save a graph in the graph6 format in Python using networkx

I try to save a graph in graph6 format in Python with networkx. The obvious way does not seem to work:
import networkx as nx
g = nx.Graph()
g.add_edge('1','2')
nx.write_graph6(g,"anedge.g6")
g1 = nx.read_graph6("anedge.g6")
import matplotlib.pyplot as plt
nx.draw(g1)
plt.savefig("anedge.pdf")
This makes a pdf file showing a graph with two isolated vertices instead of two connected vertices.
Using g.add_edge(0, 1) instead of g.add_edge('1','2') it should work:
import networkx as nx
import matplotlib.pyplot as plt
g = nx.Graph()
g.add_edge(0, 1)
nx.write_graph6(g, 'anedge.g6')
g1 = nx.read_graph6('anedge.g6')
nx.draw(g1)
plt.savefig("anedge.pdf")
This is actually exposing a bug in the networkx graph6 generator when the nodes are not consecutively ordered from zero. Bug fix is here https://github.com/networkx/networkx/pull/2739

How to use Networks(python) draw method?

My code as follows:
import ConfigParser
import sys
import time
import matplotlib.pyplot as plt
import networkx as nx
import json
from networkx.algorithms import bipartite
def create_graph(senators):
G= nx.Graph()
G.add_nodes_from(senators)
return G
senators=["ab","cd","ef"]
graph = create_graph(senators)
nx.draw(graph,with_labels=True)
plt.savefig("p1.png")
graph.clear()
graph = nx.DiGraph()
print graph.nodes()
nx.draw(graph,with_labels=True)
plt.savefig("p2.png")
In my code I try to draw two pictures:p1.png and p2.png. After I draw p1.png , I clear graph. However, p2.png has the same node with p1.png.
I don't know what's wrong with my code . Because I have clear graph, so there should be nothing in p2.png
What is the problem?
There are two separate notions of "clearing". One is removing nodes and edges from the graph (graph.clear) and the other is erasing the figure (plt.clf()). You are removing the nodes and edges but not clearing the figure axes. So what you are saving in p2.png is just the original p1.png figure. Try adding a plt.clf() before the second nx.draw().

Categories

Resources