我能够使用geopandas读取形状文件,但我想用一种州的不同颜色为不同的城市着色,如何为一种州的不同城市着色呢?谢谢。
import geopandas as gpd
gf_states = gpd.read_file('IND_adm2.shp')
gr_states.head()
ID_0 ISO NAME_0 ID_1 NAME_1 ID_2 NAME_2 TYPE_2 ENGTYPE_2 NL_NAME_2 VARNAME_2 geometry
0 105 IND India 1 Andaman and Nicobar 1 Andaman Islands District District None None MULTIPOLYGON (((93.64841 14.93487, 93.64917 14...
1 105 IND India 1 Andaman and Nicobar 2 Nicobar Islands District District None None MULTIPOLYGON (((92.78778 9.24417, 92.78889 9.2...
2 105 IND India 2 Andhra Pradesh 3 Anantapur District District None Anantpur, Ananthapur POLYGON ((77.69000 15.17628, 77.69378 15.17347...
3 105 IND India 2 Andhra Pradesh 4 Chittoor District District None Chitoor|Chittor POLYGON ((78.47611 13.93680, 78.48208 13.93007...
4 105 IND India 2 Andhra Pradesh 5 Cuddapah District District None None POLYGON ((78.94612 15.19465, 78.95062 15.18535...
这里假设我要给NAME_2上色(阿纳塔普尔用红色,红色的chittor用蓝色,黄色的cuddapah用黄色,等等,这样一个州NAME_1安得拉邦)。我该怎么做?谢谢。我正在下面处理的代码:-
def fig_beauty_hires(ax,xlim=[66,78],ylim=[20,24],st_name,states=False,states_name=False):
import cartopy as crs
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import geopandas as gpd
gf_states = gpd.read_file('IND_adm2.shp')
gdff = gf_states.loc[gf_states['NAME_1']==st_name,['geometry','NAME_2']]
if states_name:
gf_new = gdff.cx[xlim[0]:xlim[1],ylim[0]:ylim[1]]
state_points = gf_new.geometry.apply(lambda x :x.representative_point().coords[:])
state_coords = [point[0] for point in state_points]
cMap = ['#00FF00','#FFFF00','#00FFFF','#FF00FF','#FF4500','#7B68EE','#ADFF2F']
for name, coord , col,j in zip(gf_new.NAME_2,state_coords,cMap,range(0,len(cMap))):
#print(name)
#ax.add_geometries(gdff.geometry,crs=ccrs.PlateCarree(),color=cMap[j],edgecolor='k')
if name=="Nashik" or name=="Aurangabad"or name=="Jalna" or name=="Osmanabad"or name=="Gadag"or name=="Bellary"or name=="Mysore" or name=="Davanagere" or name=="Hassan" or name=="Greater Bombay"or name=="Thiruvananthapuram"or name=="Alappuzha" or name=="Kollam" or name=="Pattanamtitta" or name=="Idukki" or name=="Palakkad":
print("if j:",str(cMap[j]))
ax.add_geometries(gdff.geometry,crs=ccrs.PlateCarree(),facecolor=cMap[j],edgecolor='k')
ax.text(x=coord[0],y=coord[1],s=" ",horizontalalignment='center',fontweight='normal',fontsize=10,color='k')
else:
print("else j:",str(cMap[j]))
ax.add_geometries(gdff.geometry,crs=ccrs.PlateCarree(),facecolor=cMap[j],edgecolor='k')
ax.text(x=coord[0],y=coord[1],s=name,horizontalalignment='center',fontweight='bold',fontsize=10,color='k')
if __name__=="__main__":
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
fig, ax = plt.subplots(figsize=(19.20,10.80), subplot_kw={'projection': ccrs.PlateCarree()})
fig_beauty_hires(ax=ax)
尚不完全清楚,您期望的最终输出是什么。而且您发布的代码无法运行(即使我们忽略了多次导入等)。
我的理解是,您希望绘制一些几何图形,以便能够控制每个几何图形的facecolor
。这是一个可以构建的简单代码段:(我设法找到一个与您发布的数据集匹配的数据集。)
import geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
# Obtain the data & keep only relevant attributes
states = gpd.read_file('gadm36_IND.gpkg', layer=1)[['NAME_1', 'NAME_2', 'geometry']]
# Prepare the data for easy manipulations later
df = states[states.NAME_1 == 'Andhra Pradesh']
df.reset_index(inplace=True, drop=True) #for later convenience
# Prepare the projections
data_crs = ccrs.PlateCarree() # this will be fixed by your data
proj_crs = ccrs.PlateCarree() # this determines the projection of the plot
extents = [75, 86, 12, 20] # change as needed depending on the data
# Produce the main figure and axis
fig = plt.figure(figsize=(15, 15))
ax = fig.add_subplot(projection=proj_crs)
# Some configuration
ax.set_extent(extents, crs=data_crs)
ax.coastlines() # just for (some) spatial reference only
# Plot the geometries. A very basic plotting scheme shown here
colours = ['red', 'green', 'yellow'] # (almost) randomly selected
for index, row in df.iterrows():
sp = ShapelyFeature(row.geometry, data_crs,
edgecolor='k', linewidth=0.5,
facecolor=colours[index%len(colours)])
ax.add_feature(sp)
locxy = row.geometry.representative_point()
ax.annotate(row.NAME_2, xy=(locxy.x, locxy.y)) # use transform for other projections
plt.show()