使用 Python 的 matplotlib/basemap 进行颜色状态

发布于 2024-12-07 01:22:58 字数 56 浏览 0 评论 0原文

我想生成一张美国地图,并使用不同的阴影为每个州着色。有没有办法使用Python的底图来做到这一点?

I want to generate a map of the United States and color each state in using a different shade. Is there a way to do this using Python's basemap?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海风掠过北极光 2024-12-14 01:22:58

GitHub 上的底图存储库中有一个格式良好的示例:fillstates.py。 shapefile (dbf | shp | shx) 也包含在 示例文件夹

以下是该示例的缩写版本:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon

# create the map
map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
        projection='lcc',lat_1=33,lat_2=45,lon_0=-95)

# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)

# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
    state_names.append(shape_dict['NAME'])

ax = plt.gca() # get current axes instance

# get Texas and draw the filled polygon
seg = map.states[state_names.index('Texas')]
poly = Polygon(seg, facecolor='red',edgecolor='red')
ax.add_patch(poly)

plt.show()

德克萨斯州填充红色的结果图:

德克萨斯州填充红色的结果图

请注意,当我们加载 shapefile,形状和属性分别存储在 map.statesmap.states_info 中,作为基于中使用的 name 参数的列表readshapefile 调用。因此,要查找特定状态的形状,我们必须根据属性构建相应的状态名称列表。

There is a nicely formated example in the Basemap repo on GitHub: fillstates.py. The shapefile (dbf | shp | shx) is also included in the examples folder.

Here is an abbreviated version of the example:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon

# create the map
map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
        projection='lcc',lat_1=33,lat_2=45,lon_0=-95)

# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)

# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
    state_names.append(shape_dict['NAME'])

ax = plt.gca() # get current axes instance

# get Texas and draw the filled polygon
seg = map.states[state_names.index('Texas')]
poly = Polygon(seg, facecolor='red',edgecolor='red')
ax.add_patch(poly)

plt.show()

Resulting plot with Texas filled red:

Resulting plot with Texas filled red

Note that when we load a shapefile the shapes and attributes are stored in map.states and map.states_info respectively as lists based on the name parameter used in the readshapefile call. So to look up the shape for a specific state we had to build a corresponding list of the state names from the attributes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文