使用Cartopy添加地图网格线遇问题:官方示例代码不符合需求
Ah, I recognize this issue—Cartopy's gridlines can be tricky when working with non-PlateCarree projections like Mercator, especially when using a Pacific-centered extent. Let's walk through fixing this step by step.
First, let's recap your code (filling in the truncated feature addition for context):
import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt def plotMap(): proj = ccrs.Mercator(central_longitude=180, min_latitude=15, max_latitude=55) fig, ax = plt.subplots(subplot_kw=dict(projection=proj), figsize=(12,12)) ax.set_extent([255 ,115, 0, 60], crs=ccrs.PlateCarree()) ax.add_feature(cfeature.LAND, facecolor='0.3') # Truncated feature addition (e.g., ax.add_feature(cfeature.OCEAN))
Common Gridline Problems in Your Setup
- CRS Mismatch: By default,
ax.gridlines()uses the axes' projection (Mercator here), which draws projection-specific lines instead of the geographic latitude/longitude lines you likely want. - Pacific-Centered Extent Issues: Your longitude range (255°E to 115°E, equivalent to -105°W to 115°E) wraps the date line, which default gridlines don't handle well.
- Missing Label Control: Official examples often skip label customization, leading to overlapping or missing labels.
Fixed Code with Proper Gridlines
Here's the adjusted code to get clean, labeled geographic gridlines:
import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt def plotMap(): proj = ccrs.Mercator(central_longitude=180, min_latitude=15, max_latitude=55) fig, ax = plt.subplots(subplot_kw=dict(projection=proj), figsize=(12,12)) # Pacific-centered extent (255°E to 115°E = -105°W to 115°E) ax.set_extent([255, 115, 0, 60], crs=ccrs.PlateCarree()) # Add base map features ax.add_feature(cfeature.LAND, facecolor='0.3') ax.add_feature(cfeature.OCEAN, facecolor='lightblue') ax.add_feature(cfeature.COASTLINE, linewidth=0.5) # Add geographic gridlines (using PlateCarree CRS for lat/lon) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linestyle='--', color='gray', alpha=0.7) # Customize label placement (standard map convention) gl.top_labels = False gl.right_labels = False gl.xlabel_style = {'size': 10, 'color': 'black'} gl.ylabel_style = {'size': 10, 'color': 'black'} # Explicitly set grid positions to fit your Pacific-centered view gl.xlocator = plt.FixedLocator([180, 150, 120, 90, 60, 30, 0, -30, -60, -90, -120]) gl.ylocator = plt.FixedLocator([10,20,30,40,50,60]) plt.show() plotMap()
Key Adjustments Explained
crs=ccrs.PlateCarree(): Ensures gridlines are drawn as true geographic latitude/longitude lines, not Mercator-specific parallels.- Label Customization: Hides top/right labels for readability, and adjusts font styling for clarity.
- Fixed Locators: Explicitly defines grid positions to avoid missing labels or awkward spacing in the Pacific-centered view.
- Styling: Uses dashed gray lines with transparency to keep gridlines visible but not overwhelming the map.
Additional Tips
- If labels overlap, use
gl.x_inline=Falseorgl.y_inline=Falseto prevent inline label placement. - For rotated projections, try
gl.rotate_labels=Falseto keep labels horizontal. - To use tick marks instead of full gridlines, replace
gridlines()withax.set_xticks()/ax.set_yticks()(withcrs=ccrs.PlateCarree()) followed byax.grid().
内容的提问来源于stack exchange,提问作者Eli Turasky
相关产品推荐
相关产品推荐

