Question

I have a graph made in NetworkX. In the graph there are saved some (x,y) positions of a shape. I want to keep in the graph the normal (x,y) positions found in a shape recognition script but when I draw the graph I want to draw it at (x, height-y) positions, where height is the height of the picture. This is needed because if I draw the graph with the normal (x,y) positions, the shape is shown all the way around. So here is the code I wrote:

#ap is the array containing the (x,y) positions of the shape. x=ap[0][0], y=ap[0][1] and so on.
pe = nx.Graph()
pe.add_node('p1', posxy=(ap[0][0], ap[0][1]))
pe.add_node('p2', posxy=(ap[1][0], ap[1][1]))
pe.add_node('p3', posxy=(ap[2][0], ap[2][1]))
pe.add_node('p4', posxy=(ap[3][0], ap[3][1]))
pe.add_node('p5', posxy=(ap[4][0], ap[4][1]))
pe.add_cycle(['p1','p2','p3','p4','p5'])
positions = nx.get_node_attributes(pe, 'posxy')
nx.draw(pe, positions, labels=positions, font_size=8, font_weight='bold', node_color='yellow', alpha=0.5)

when I try to modify the variable positions it doesn't work. I tried to do something like: height-'posxy'[1] to update only the y component of posxy, but it does not work. It returns this error: unsupported operand type(s) for -: 'int' and 'str', so I don't know how to update the attribute 'posxy' for the nodes.

How can I do it?

Any help is apreciated.

Was it helpful?

Solution

The expression

height - 'posxy'[1]

Would evaluate to

height - 'o'

hence the error you are seeing.

According to the documentation, positions will be a dictionary {node: posxy, ...}.

posxy is a tuple, e.g. (1, 2), which is immutable, so you can't simply assign to one of the values (e.g. posxy[1] = ...); you will get a an error here too:

TypeError: 'tuple' object does not support item assignment 

Instead, process all of them, creating a new tuple for each position using e.g. a dictionary comprehension:

positions = {k: (v[0], height - v[1]) for k, v in positions.items()}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top