首页 > 解决方案 > 如何从网格化的 cartopy geopandas 图中从“Y”和“X”轴编辑“文本”对象

问题描述

这个问题来自另一个 Stackoverflow 问题1

我的问题是关于 cartopy-geopandas 图中 X 和 Y 轴刻度标签的版本。我想根据特定规则从我的每个刻度标签(X 和 Y 轴)更改我的文本对象。

例如,我想将 X 和 Y 轴刻度标签中的小数分隔符 ('.') 更改为逗号分隔符 (',')。

这是一个不能这样做的代码:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import geopandas as gpd

Geopandas_DF = gpd.read_file('my_file.shp')

# setting projection and Transform
Projection=ccrs.PlateCarree()
Transform = ccrs.Geodetic(globe=ccrs.Globe(ellipse='GRS80'))

Fig, Ax = plt.subplots(1,1, subplot_kw={'projection': Projection})

Geopandas_DF.plot(ax=Ax, transform=Ax.transData)

gl = Ax.gridlines(crs=Projection , draw_labels=True, linewidth=0.5, 
                  alpha=0.4, color='k', linestyle='--')

gl.top_labels = False
gl.right_labels = False


### Creating a function to change my Ticklabels:

def Ticker_corrector(ax):
        """
    Parameter:ax, axes whose axis X and Y should be applied the function

        """


    ## Correcting the Axis X and Y of the main Axes

        Xticks = ax.get_xticklabels()

        for i in Xticks:
            T = i.get_text()
            T = T.replace('.',',')
            i = i.set_text(T)

            print(T)

        ax.set_xticklabels(Xticks)



        ## Correcting the Axis Y

        Yticks = ax.get_yticklabels()

        for i in Xticks:
            T = i.get_text()
            T = T.replace('.',',')
            i = i.set_text(T)

            print(T)

        ax.set_yticklabels(Yticks)

        return ax

Ax = Ticker_corrector(Ax)

Fig.show()


上面代码的一个有趣部分是它可以毫无问题地运行。Python 没有指出其中有任何错误,它绘制图形时没有任何错误警告。

尽管如此,Ticklabels 保持不变。因此,我需要帮助解决这个问题。

我感谢你的时间。

您忠诚的,

标签: matplotlibgeopandascartopy

解决方案


我相信我已经找到了解决办法。它可能并不总是有效,但它确实解决了我的问题。

该解决方案的基本基础是在创建我的绘图之前设置我的 matplotlib 的“语言环境”。

这是一个例子:

import locale
locale.setlocale(locale.LC_ALL, "Portuguese_Brazil.1252")
import matplotlib as mpl
mpl.rcParams['axes.formatter.use_locale'] = True


import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import geopandas as gpd

Geopandas_DF = gpd.read_file('my_file.shp')

# setting projection and Transform
Projection=ccrs.PlateCarree()
Transform = ccrs.Geodetic(globe=ccrs.Globe(ellipse='GRS80'))

Fig, Ax = plt.subplots(1,1, subplot_kw={'projection': Projection})

Geopandas_DF.plot(ax=Ax, transform=Ax.transData)

gl = Ax.gridlines(crs=Projection , draw_labels=True, linewidth=0.5, 
                  alpha=0.4, color='k', linestyle='--')

gl.top_labels = False
gl.right_labels = False


Fig.show()


推荐阅读