gpt4 book ai didi

python - cartopy + networkx : zorder is not working

转载 作者:行者123 更新时间:2023-12-03 20:20:29 31 4
gpt4 key购买 nike

我需要使用 cartopy 生成 map 并在其上绘制一些数据(使用 networkx)。我能够做到,但 networkx 对象位于 map 后面。我正在尝试使用 zorder 强制图层的顺序,但是......它不起作用:(

我唯一的想法是为 cartopy 几何图形添加一些透明度,但它看起来一点也不好看......(在这个例子中它看起来并不那么糟糕,但是我的整个数据,看起来很糟糕)

关于如何强制命令的任何想法?

这是我的代码:

import cartopy.crs as ccrs
from cartopy.io import shapereader as shpreader
import matplotlib.pyplot as plt
import networkx as nx

paises = ['Portugal', 'France', 'Canada', 'Brazil', 'Kazakhstan']
cidades = ['Aveiro', 'Ust-Kamenogorsk', 'Manaus']
links = [('Aveiro', 'Ust-Kamenogorsk'),
('Manaus', 'Ust-Kamenogorsk'),
('Aveiro', 'Manaus')]
position = {'Aveiro': (-8.65, 40.6),
'Manaus': (-60.0, -3.1),
'Ust-Kamenogorsk': (82.6, 49.97)}

# map using cartopy:
shapename = 'admin_0_countries'
countries_shp = shpreader.natural_earth(resolution='110m',
category='cultural', name=shapename)

ax = plt.axes(projection=ccrs.PlateCarree(central_longitude=0.0, globe=None))
ax.set_global()

for country in shpreader.Reader(countries_shp).records():
nome = country.attributes['name_long']
if nome in paises:
i = paises.index(nome)
artist = ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor='yellow',
#alpha=0.5,
zorder=10)
else:
artist = ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor='0.9',
zorder=10)

# add some data over the cartopy map (using networkx):
G = nx.Graph()
G.add_nodes_from(cidades)
G.add_edges_from(links)

nx.draw_networkx_nodes(G, position, node_size=20, nodelist=cidades, zorder=20)
edges=nx.draw_networkx_edges(G, position, edgelist=links, zorder=20)

plt.show()

这是我得到的图像:zorder not working with networkx over cartopy

最佳答案

发生的事情是您的 zorder=20 没有做任何事情;正如您在他们的源代码中看到的那样,它被忽略了。 networkxtheir draw_networkx_edges code 中的作用是:

def draw_networkx_edges(G, pos,
...
edge_collection.set_zorder(1) # edges go behind nodes
...

their draw_networkx_nodes code是:

def draw_networkx_nodes(G, pos,
...
node_collection.set_zorder(2)
...

现在,解决方案很简单:

  • 如果您将 add_geometries 中的 zorder 设置为 1,则节点将位于 map 的前面,因为它是 zorder 2。但边是仍然在 map 后面,因为它是 zorder 1。
  • 现在真正更好的解决方案是先获取 node_collection 和 edge_collection:

    nodes = nx.draw_networkx_nodes(G, position, node_size=20, nodelist=cidades)
    edges = nx.draw_networkx_edges(G, position, edgelist=links)

    然后 set_zorder 用于节点和边:

    nodes.set_zorder(20)
    edges.set_zorder(20)

关于python - cartopy + networkx : zorder is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45203193/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com