Matplotlib:如何为列表内所有国家分配随机颜色绘制在地图上?
问题原因
- 现有代码中
color=np.random.rand(3,)只生成了1组RGB颜色值,会被应用到所有筛选出的国家几何对象上,因此所有目标国家显示为同一颜色。
修正方案
两种实现方式可选:
方式1:逐一遍历国家分配随机颜色
逻辑直观易理解,适合目标国家数量较少的场景:
import matplotlib.pyplot as plt import numpy as np import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax2 = world.plot(figsize=(15,15), edgecolor=u'white', color='gray') countries = ['Germany', 'Norway', 'Russia', 'China', 'Japan'] # 逐个国家绘制,每个国家生成独立随机色 for country in countries: country_geo = world[world['name'] == country] country_geo.plot(edgecolor=u'white', color=np.random.rand(3,), ax=ax2) ax2.axis('scaled') plt.show()
方式2:批量添加颜色列后一次性绘制
避免多次调用plot接口,目标国家数量较多时运行效率更高:
import matplotlib.pyplot as plt import numpy as np import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax2 = world.plot(figsize=(15,15), edgecolor=u'white', color='gray') countries = ['Germany', 'Norway', 'Russia', 'China', 'Japan'] # 筛选目标国家子集 target_countries = world[world['name'].isin(countries)].copy() # 为每个行生成独立的随机颜色 target_countries['color'] = [np.random.rand(3,) for _ in range(len(target_countries))] # 用自定义颜色列绘制 target_countries.plot(edgecolor=u'white', color=target_countries['color'], ax=ax2) ax2.axis('scaled') plt.show()
内容的提问来源于stack exchange,提问作者Witness1123
相关产品推荐
相关产品推荐

