如何使用路线的距离创建颜色图

DPM

当前,我有一张图显示了网络中所有节点与目标之间的所有最短路径:情节现在,我想制作一个cmap,在其中根据最短路径的距离为原始节点和边缘着色。谁能帮我?

这是我所拥有的:

import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
import geopandas as gpd
from shapely.wkt import loads as load_wkt

ox.config(log_console=True, use_cache=True)

place = {'city': 'Lisbon', 'country': 'Portugal'}
G = ox.graph_from_place(place, network_type='drive')
G = ox.project_graph(G)
hospitals = ox.pois_from_place(place, amenities=['hospital'])

hosp_1 = hospitals.iloc[21]['geometry']  # Hospital Santa Maria (Polygon)


def poly_centroide(polygon):

# Gives me the coordinates of the center point of the Polygon

    p1 = load_wkt(polygon)
    centroide = p1.centroid.wkt

    return centroide

polygon_1 = str(hosp_1)

coord_1_str = poly_centroide(polygon_1)


coord_1 = (38.74817825481225, -9.160815118526642)  # Coordinates Hospital Santa Maria


target_1 = ox.get_nearest_node(G, coord_1)


routes = []
for node in G.nodes:
    try:
        route = nx.shortest_path(G, node, target_1)
        routes.append(route)
    except nx.exception.NetworkXNoPath:
        continue

fig, ax = ox.plot_graph_routes(G, routes, edge_linewidth=0.2, node_size=5, route_linewidth=1)
plt.show()

现在,我想知道如何创建cmap,其中节点和边缘的颜色基于最短路径的距离。

我怀疑可以用nx.dra()完成,但是我不知道如何...

先感谢您。

德布吉·博米克(Debjit Bhowmick)

I have slightly added to your code. This will help in colouring the nodes based on their topological distance (since you did not pass any specific weight while calculating the shortest path, the shortest path is calculated based on the number of edges needed to be traversed to reach the destination as each edge is assigned a weight of 1).

I start after target_1 = ox.get_nearest_node(G, coord_1)

Obtain the nodes and edges geodataframes from the graph. We need the nodes geodataframe for this purpose.

nodes, edges = ox.graph_to_gdfs(G, nodes=True, edges=True)

We then calculate the shortest path, the shortest path length, and assign the latter to a new column in the nodes geodataframe.

nodes['shortest_route_length_to_target'] = 0
routes = []
route_lengths = []
i = 0
for node in G.nodes:
    try:
        route = nx.shortest_path(G, node, target_1)
        route_length = nx.shortest_path_length(G, node, target_1)
        routes.append(route)
        route_lengths.append(route_length)
        nodes['shortest_route_length_to_target'][node] = route_length
    except nx.exception.NetworkXNoPath:
        continue

Now we define the following functions. You will notice that these functions are the ones already existing in the file plot.py but are slightly modified for this purpose.

import numpy as np
import matplotlib.cm as cm

def get_colors(n, cmap='viridis', start=0., stop=1., alpha=1.,):

    colors = [cm.get_cmap(cmap)(x) for x in np.linspace(start, stop, n)]
    colors = [(r, g, b, alpha) for r, g, b, _ in colors]
    return colors


def get_node_colors_by_attr(G, attr, num_bins=None, cmap='viridis', start=0, stop=1, na_color='none'):

    if num_bins is None:
        num_bins=len(G.nodes())
    bin_labels = range(num_bins)
    # attr_values = pd.Series([data[attr] for node, data in G.nodes(data=True)])
    attr_values = pd.Series(nodes[attr].values)
    cats = pd.qcut(x=attr_values, q=num_bins, labels=bin_labels)
    colors = get_colors(num_bins, cmap, start, stop)
    node_colors = [colors[int(cat)] if pd.notnull(cat) else na_color for cat in cats]
    return node_colors

Now the following lines of code will give you your desired output.

nc = get_node_colors_by_attr(G, attr = 'shortest_route_length_to_target', num_bins=20,)
fig, ax = ox.plot_graph(G, node_color = nc, fig_height=20,)

在此处输入图片说明

您可以更改颜色图(cmap)或num_bins希望将route_lengths离散化到的仓数(

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

创建单边距离图

来自分类Dev

如何使用 matplotlib 创建圆形 2D 图,其中函数取决于与图像中心的距离?

来自分类Dev

如何使用随机距离矩阵构建图?

来自分类Dev

如何为图创建更多颜色?

来自分类Dev

OpenGL:如何创建颜色图纹理?

来自分类Dev

使用颜色图根据图像的亮度图创建PIL图像

来自分类常见问题

使用matplotlib创建自己的颜色图并绘制颜色比例

来自分类Dev

如何在不同颜色的iOS中使用uibezierpath创建堆叠条形图

来自分类Dev

我正在使用seaborn,并有一个热图。如何创建具有离散范围内特定颜色的颜色图?

来自分类Dev

如何更改用Chartkick创建的柱形图的颜色?

来自分类Dev

如何创建这条路线?

来自分类Dev

使用Matplotlib颜色图

来自分类Dev

使用Matplotlib颜色图

来自分类Dev

如何从两种颜色创建插值的颜色图或调色板?

来自分类常见问题

如何使用jgrapht创建子图

来自分类Dev

如何使用HighCharts创建“开/关”图?

来自分类Dev

如何使用GraphViz DOT创建循环图?

来自分类Dev

如何使用Bokeh创建饼图?

来自分类Dev

如何使用highchart图自动创建pdf

来自分类Dev

如何使用python创建简单的饼图

来自分类Dev

如何使用matplotlib创建群图

来自分类Dev

如何使用Vega创建Cladogram图?

来自分类Dev

如何使用QCharts创建子图?

来自分类Dev

如何使用pvc创建postgres掌舵图

来自分类Dev

如何使用python创建饼图?

来自分类Dev

如何使用ChartJS创建堆积图

来自分类Dev

如何使用 Rstudio flexdashboard 创建饼图?

来自分类Dev

如何使用 matplotlib 创建购买活动图?

来自分类Dev

如何使用Svelte Routify创建路线链接