使用 Cartopy 添加网格线 [英] Adding gridlines using Cartopy

查看:193
本文介绍了使用 Cartopy 添加网格线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将网格线添加到我使用 Cartopy 制作的地图中,但是,当我使用 Cartopy 文档中的示例代码时,它没有显示我想要的内容,我无法弄清楚如何操作它为此.

def plotMap():proj = ccrs.Mercator(central_longitude = 180,min_latitude = 15,最大纬度=55)无花果,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')ax.add_feature(cfeature.LAKES,alpha=0.9)ax.add_feature(cfeature.BORDERS, zorder=10)ax.add_feature(cfeature.COASTLINE,zorder = 10)#(http://www.naturalearthdata.com/features/)States_provinces = cfeature.NaturalEarthFeature(category =文化",名称="admin_1_states_provinces_lines",scale ='50m',facecolor ='none')ax.add_feature(states_provinces, edgecolor='black', zorder=10)#ax.gridlines(xlocs=grids_ma, ylocs=np.arange(-80,90,20), zorder=21,draw_labels=True )ax.gridlines(crs = ccrs.PlateCarree(),linewidth = 2,color ='black',draw_labels=True, alpha=0.5, linestyle='--')ax.xlabels_top =假ax.ylabels_left = Falseax.ylabels_right =真实ax.xlines =真ax.xlocator = mticker.FixedLocator([-160, -140, -120, 120, 140, 160, 180,])ax.xformatter = LONGITUDE_FORMATTERax.yformatter = LATITUDE_FORMATTERax.xlabel_style = {'大小':15,'颜色':'灰色'}ax.xlabel_style = {'颜色':'红色','重量':'粗体'}返回无花果,斧头

我附上了输出的图片.作为参考,我只希望经度网格线从域的左侧开始,在右侧结束,最好每20度间隔一次.理想情况下,纬度线也是如此.

另一种方法是直接使用matplotlib设置各种标签及其样式.请注意,您必须将刻度标签与刻度分开设置,否则您将获得与墨卡托坐标参考系统相对应的标签:

 将cartopy.mpl.ticker导入为ctickerdef plotMap2():proj = ccrs.Mercator(central_longitude = 180,min_latitude = 15,最大纬度=55)无花果,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')ax.add_feature(cfeature.LAKES,alpha=0.9)ax.add_feature(cfeature.BORDERS, zorder=10)ax.add_feature(cfeature.COASTLINE,zorder=10)States_provinces = cfeature.NaturalEarthFeature(类别='文化',名称='admin_1_states_provinces_lines',scale='50m', facecolor='none')ax.add_feature(states_provinces, edgecolor='black', zorder=10)ax.set_xticks([120.,140.,160.,180.,-160.,-140.,-120.],crs = ccrs.PlateCarree())ax.set_xticklabels([120.,140.,160.,180.,-160.,-140.,-120.],color ='red',weight ='bold')ax.set_yticks([20,40],crs = ccrs.PlateCarree())ax.set_yticklabels([20,40])ax.yaxis.tick_right()lon_formatter = cticker.LongitudeFormatter()lat_formatter = cticker.LatitudeFormatter()ax.xaxis.set_major_formatter(lon_formatter)ax.yaxis.set_major_formatter(lat_formatter)ax.grid(linewidth=2, color='black', alpha=0.5, linestyle='--')

I'm trying to add gridlines to a map I made using Cartopy, however, when I use the example code from the cartopy documentation, it doesn't display what I want and I can't figure out how to manipulate it to do so.

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')
    ax.add_feature(cfeature.LAKES, alpha=0.9)  
    ax.add_feature(cfeature.BORDERS, zorder=10)
    ax.add_feature(cfeature.COASTLINE, zorder=10)


    #(http://www.naturalearthdata.com/features/)
    states_provinces = cfeature.NaturalEarthFeature(
            category='cultural',  name='admin_1_states_provinces_lines',
            scale='50m', facecolor='none')
    ax.add_feature(states_provinces, edgecolor='black', zorder=10)

    #ax.gridlines(xlocs=grids_ma, ylocs=np.arange(-80,90,20), zorder=21, 
    draw_labels=True ) 
    ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, color='black', 
    draw_labels=True, alpha=0.5, linestyle='--')
    ax.xlabels_top = False
    ax.ylabels_left = False
    ax.ylabels_right=True
    ax.xlines = True
    ax.xlocator = mticker.FixedLocator([-160, -140, -120, 120, 140, 160, 180,])
    ax.xformatter = LONGITUDE_FORMATTER
    ax.yformatter = LATITUDE_FORMATTER
    ax.xlabel_style = {'size': 15, 'color': 'gray'}
    ax.xlabel_style = {'color': 'red', 'weight': 'bold'}


    return fig, ax

I've attached a picture of the output. For reference, I only want the longitude gridlines to start at the left of my domain and end at the right side, preferably being spaced every 20 degrees. Ideally the same for latitude lines as well. Bad gridline plot

解决方案

Is the example you are following the one at the bottom of this page? If so, you are attempting to set attributes on the GeoAxes (ax) instance which should be set on the GridLiner (gl) instance:

import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER

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')
    ax.add_feature(cfeature.LAKES, alpha=0.9)  
    ax.add_feature(cfeature.BORDERS, zorder=10)
    ax.add_feature(cfeature.COASTLINE, zorder=10)

    states_provinces = cfeature.NaturalEarthFeature(
            category='cultural',  name='admin_1_states_provinces_lines',
            scale='50m', facecolor='none')
    ax.add_feature(states_provinces, edgecolor='black', zorder=10)   

    gl = ax.gridlines(crs=ccrs.PlateCarree(), linewidth=2, color='black', alpha=0.5, linestyle='--', draw_labels=True)
    gl.xlabels_top = False
    gl.ylabels_left = False
    gl.ylabels_right=True
    gl.xlines = True
    gl.xlocator = mticker.FixedLocator([120, 140, 160, 180, -160, -140, -120])
    gl.ylocator = mticker.FixedLocator([0, 20, 40, 60])
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'color': 'red', 'weight': 'bold'}

This produces the following map. The gridliner doesn't seem to be coping with the dateline. I do not know if there is a way around this, but there is a note at the top of the above linked documentation to say that there are currently known limitations with this class, so maybe not.

An alternative is to set the various labels and their styles directly with matplotlib. Note that you have to set the ticklabels separately from the ticks, otherwise you get labels corresponding to the Mercator coordinate reference system:

import cartopy.mpl.ticker as cticker

def plotMap2():
    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')
    ax.add_feature(cfeature.LAKES, alpha=0.9)  
    ax.add_feature(cfeature.BORDERS, zorder=10)
    ax.add_feature(cfeature.COASTLINE, zorder=10)

    states_provinces = cfeature.NaturalEarthFeature(
            category='cultural',  name='admin_1_states_provinces_lines',
            scale='50m', facecolor='none')
    ax.add_feature(states_provinces, edgecolor='black', zorder=10)

    ax.set_xticks([120., 140., 160., 180., -160., -140., -120.], crs=ccrs.PlateCarree())
    ax.set_xticklabels([120., 140., 160., 180., -160., -140., -120.], color='red', weight='bold')
    ax.set_yticks([20, 40], crs=ccrs.PlateCarree())
    ax.set_yticklabels([20, 40])
    ax.yaxis.tick_right()

    lon_formatter = cticker.LongitudeFormatter()
    lat_formatter = cticker.LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)
    ax.grid(linewidth=2, color='black', alpha=0.5, linestyle='--')

这篇关于使用 Cartopy 添加网格线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆