I would like to know how I can make the graph go straight and not tilted as it is. I'm doing it with the Jupyter IDE and Python 3.6.
This is the code:
import networkx
gP = { 1: [2,5,6], 2: [3,1,7], 3: [4,2,8], 4: [5,3,9], 5: [1,4,10],6: [1,8,9],
7:[2,9,10], 8: [3,10,6], 9: [4,6,7], 10: [5,7,8] }
for k in gP:
gP[k].append(-1)
gP[k].append(-2)
gP[-1] = list(range(1,11))
gP[-2] = list(range(1,11))
rH = [8, 3, 4, 5, 10, 7, 2, 1, 6, 9];
g = networkx.Graph()
for k, vs in gP.items():
for v in vs:
if v in [-1, -2] or k in [-1, -2]:
continue
if abs(rH.index(k) - rH.index(v)) == 1:
g.add_edge(k,v, color='red', width=1.5)
else:
g.add_edge(k,v, color='black', width=0.5)
posicion = networkx.circular_layout(g)
edges = g.edges()
colors = [g[u][v]['color'] for u,v in edges]
width = [g[u][v]['width'] for u,v in edges]
networkx.draw_shell(g, nlist=[range(6,11), range(1,6)], edge_color=colors, width=width, with_labels = True)
Thank you very much.
In the code you have shown there is a line that says:
This line is used to calculate an arrangement of the nodes (the coordinates
x,y
in which each of them should be drawn), so that they are organized in the form of a circle.Actually, this line is superfluous, because you don't do anything afterwards with the positions you have calculated, since in fact you paint the graph following another layout, called "shell". When you call the function
draw_shell()
, this function internally calls tonetworkx.shell_layout()
calculate where each node would go (arranging them in this case in several circular layers), and also paints the result.We can explicitly separate these two operations: first calculate where the nodes would go, according to a "layered" ( shell ) arrangement:
and then paint it at those positions (note that I now use
draw()
instead ofdraw_shell()
:The result for now is the same as it would come out with your code:
If there were some way to ask
networkx.shell_layout()
it to rotate the node positions, before askingnetworkx.draw()
it to draw it, we'd have what you're looking for. Unfortunately, the functions that calculate the arrangement of the nodes do not support any parameters that allow the result to be rotated.But doing it in two stages allows us to rotate it "by hand", so to speak, since the variable
posiciones
is a dictionary whose keys are the names of the nodes (numbers in this case) and whose values are the coordinatesx,y
(in the form of a numpy array ) where each should be painted.We can therefore manipulate the positions of the nodes as we please. The following function uses matrix algebra and numpy to rotate all points of the graph about the origin by a given angle (clockwise, counterclockwise if the angle is negative):
So, to rotate your graph to the left by an angle of 360/20 (which is the amount needed in this case so that the base of the pentagon comes out horizontal, instead of one of its sides coming out vertical), the code would be: