如何添加浅灰色状态线、将背景更改为白色以及将某些区域更改为某些颜色?这是来自 EPA Level2 生态区地图。我想为每个生态区涂上单独的颜色。
import geopandas as gpd
import matplotlib.pyplot as plt
# Load the shapefile
shapefile_path = "/home/student/tsjohnson/NA_CEC_Eco_Level2.shx"
level2 = gpd.read_file(shapefile_path)
# Create the plot
ax = level2.plot(edgecolor='black', figsize=(10, 8))
# Set axis limits
ax.set_xlim([-2.25E6,-1E6])
ax.set_ylim([-1E6, 0.6E6])
# Show the plot
plt.show()
我尝试了这个,它拉伸了图像并且没有添加任何东西。
import geopandas as gpd
import matplotlib.pyplot as plt
# Load the shapefile
shapefile_path = "/home/student/tsjohnson/NA_CEC_Eco_Level2.shx"
level2 = gpd.read_file(shapefile_path)
# Create the plot with white background
fig, ax = plt.subplots(figsize=(10, 8))
level2.plot(ax=ax, edgecolor='black')
# Set axis limits
ax.set_xlim([-2.25E6, -1E6])
ax.set_ylim([-1E6, 0.5E6])
ax.set_facecolor('white')
us_states = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
states = us_states[us_states['continent'] == 'North America'] # Filter for North American states
states.boundary.plot(ax=ax, linewidth=1, color='black')
plt.show()
我建议您手动指定每种颜色以使它们正确:
import geopandas as gpd
import matplotlib.pyplot as plt
f = r"C:\Users\bera\Downloads\na_cec_eco_l2\NA_CEC_Eco_Level2.shp"
df = gpd.read_file(f)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10,10))
colormap = {"MARINE WEST COAST FOREST":"lightseagreen",
"WESTERN CORDILLERA":"limegreen",
"COLD DESERTS":"khaki",
"MEDITERRANEAN CALIFORNIA":"lightgreen",
"WARM DESERTS":"gold"}
df["color"] = df["NA_L2NAME"].map(colormap).fillna("grey")
states = gpd.read_file(r"https://raw.githubusercontent.com/PublicaMundi/MappingAPI/refs/heads/master/data/geojson/us-states.json")
states = states.to_crs(df.crs)
ax.set_xlim([-2.25E6,-1E6])
ax.set_ylim([-1E6, 0.6E6])
df.plot(figsize=(10,10), ax=ax, color=df.color, zorder=1)
states.boundary.plot(ax=ax, zorder=2, color="black")