You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:36:03