matplotlib - 如何从网格化的 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 保持不变。因此,我需要帮助解决这个问题。
我感谢你的时间。
您忠诚的,
解决方案
我相信我已经找到了解决办法。它可能并不总是有效,但它确实解决了我的问题。
该解决方案的基本基础是在创建我的绘图之前设置我的 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()
推荐阅读
- java - 无法使用 DateTimeFormatter 解析
- javascript - 为什么 Firefox 将我的数组变量视为未定义?
- azure-data-factory - 数据流单行转换
- parceljs - Parcel 输出大量微小的 es6 模块文件
- javascript - 模态对话框 cookie 弹出窗口可访问性问题
- windows - 如何更改 PrtSc (PrintScreen) 键的功能?
- encryption - 如何制作树莓派 Pico MicroPython 代码加密?
- python - 将目录条目添加到 mpl.backends.backend_pdf.PdfPages 文档
- python - 打印所有可能的字符串[1,2,3,4,5,6]:例如:(2,3,4,5,6,1) (3,4,5,6,1,2) (4, 5,6,1,2,3) 我必须在 python 中使用 for 循环来旋转每个数字
- python - 如何在 Python 中使用 docx 模块读取与 Checkbox 关联的值