【问题标题】:cartopy set_xlabel set_ylabel (not ticklabels)cartopy set_xlabel set_ylabel(不是ticklabels)
【发布时间】:2016-05-30 12:04:59
【问题描述】:

使用 cartopy 地图时,我无法添加 xlabel 或 ylabel。有没有办法做到这一点?我不是在寻找刻度标签。

import matplotlib.pyplot as plt
import cartopy
ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.add_feature(cartopy.feature.COASTLINE)
ax.set_xlabel('lon')
ax.set_ylabel('lat')
plt.show()

【问题讨论】:

    标签: python matplotlib axis-labels cartopy


    【解决方案1】:

    Cartopy 的 matplotlib gridliner 接管 xlabel 和 ylabel 并使用它来管理网格线和标签。 https://github.com/SciTools/cartopy/blob/master/lib/cartopy/mpl/gridliner.py#L93

    import matplotlib.pyplot as plt
    import cartopy
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_feature(cartopy.feature.COASTLINE)
    gridlines = ax.gridlines(draw_labels=True)
    # this would not function, due to the gridliner
    # ax.set_xlabel('lon')
    # ax.set_ylabel('lat')
    plt.show()
    

    如果你想给 cartopy 坐标轴的坐标轴实例添加标签,你应该放置它们,这样它们就不会与网格线重叠。目前需要手动完成,如:

    import matplotlib.pyplot as plt
    import cartopy
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_feature(cartopy.feature.COASTLINE)
    gridlines = ax.gridlines(draw_labels=True)
    ax.text(-0.07, 0.55, 'latitude', va='bottom', ha='center',
            rotation='vertical', rotation_mode='anchor',
            transform=ax.transAxes)
    ax.text(0.5, -0.2, 'longitude', va='bottom', ha='center',
            rotation='horizontal', rotation_mode='anchor',
            transform=ax.transAxes)
    plt.show()
    

    您需要调整 ax.text 位置的值以在每种情况下获得您想要的效果,这可能有点令人沮丧,但它很实用。

    添加到 cartopy 以自动执行此放置将是一个不错的功能。

    【讨论】:

    • 谢谢你,适用于我的应用程序。这可能是一个有用的东西。另一方面,之前没有问过;)
    【解决方案2】:

    我偶然发现它正在运行...

    import matplotlib.pyplot as plt
    import cartopy
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.set_xlabel('lon')
    ax.set_ylabel('lat')
    
    ax.set_xticks([-180,-120,-60,0,60,120,180])
    ax.set_yticks([-90,-60,-30,0,30,60,90])
    
    plt.show()
    

    ...它打印 xticks 和 yticks 以及 xlabel 和 ylabel。在 xticks 和 yticks 已经定义的其他情况下,它们将被恢复...

    ax.set_xticks(ax.get_xticks())
    ax.set_yticks(ax.get_yticks())
    

    或者如果它们是在地图限制之外自动生成的

    ax.set_xticks(ax.get_xticks()[abs(ax.get_xticks())<=180])
    ax.set_yticks(ax.get_yticks()[abs(ax.get_yticks())<=90])
    

    用于添加网格...

    plt.grid()
    

    【讨论】:

    • 这也适用于空网格:ax.set_yticks([])。使用 Python 3.7.6、Cartopy 0.17.0、Matplotlib 3.1.3 测试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    相关资源
    最近更新 更多