DPM
DPM

Reputation: 935

Coloring nodes according to an attribute in osmnx

I was trying to color the nodes of my network according to a specific attribute, however the function ox.plot.get_node_colors_by_attr() isn't work.

The error is: ValueError: There are no attribute values.

Here is the code:

import networkx as nx
import numpy as np
import osmnx as ox
ox.config(use_cache=True, log_console=True)

city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive', simplify=True)

G_nx = nx.relabel.convert_node_labels_to_integers(G)
nodes, edges = ox.graph_to_gdfs(G_nx, nodes=True, edges=True)

r_total = np.random.random(len(G_nx))
nodes['r'] = nodes.index.map(lambda x: r_total[x])
nodes.head()
nc = ox.plot.get_node_colors_by_attr(G_nx, attr='r')

Upvotes: 1

Views: 1140

Answers (1)

Sparky05
Sparky05

Reputation: 4892

If you replace the lines

nodes['r'] = nodes.index.map(lambda x: r_total[x])
nodes.head()

with

nx.set_node_attributes(G_nx, {x:r_total[x] for x in nodes.index}, name='r')

your code should work (documentation of set_node_attributes) - even if I don't understand why you assign random values in such a complicated way, but I guess this is only to have a minimal, reproducible example.

Upvotes: 1

Related Questions