python - 缩放地图时如何在子图边界外剪切文本?
问题描述
我正在使用带有 cartopy 包的 matplotlib 在 matplotlib 图的子图中显示巴基斯坦地图及其城市名称,如图 1 所示。但我的问题是,当我放大子图以查看更多细节时,一切正常,但绘制的文本(城市名称)显示在子图边界之外,如何剪切外部文本。
这是我在地图上绘制城市名称的代码。
def draw_cities(self, extent, axis):
cities_df = pd.read_csv('assets/maps/cities.csv')
# axis.plot(lons, lats, markersize=5, marker='o', linestyle='', color='#b30909', transform=ccrs.PlateCarree(),
# label='ASOS Station')
self.cities_plot = axis.scatter(cities_df.lng.values, cities_df.lat.values,
color='red', marker='.', transform=ccrs.PlateCarree())
transform = ccrs.PlateCarree()._as_mpl_transform(axis) # set transform for annotations
self.cities_text = []
# text annotations
for lat_s, lon_s, name_s in zip(cities_df.lat.values, cities_df.lng.values, cities_df.city.values): # loop through lats/lons/names
if lon_s > extent[0] and lon_s < extent[1] and lat_s > extent[2] and lat_s < extent[3]:
text = axis.text(lon_s, lat_s, name_s, {'color': 'r', 'fontsize': 6},
horizontalalignment='center', verticalalignment='bottom',
clip_on=True, transform=transform)
self.cities_text.append(text)
cartopy地图上的放大代码:
def zoom_factory(self, ax, base_scale=2.):
def zoom_fun(event):
# get the current x and y limits
cur_xlim = ax.get_xlim()
cur_ylim = ax.get_ylim()
cur_xrange = (cur_xlim[1] - cur_xlim[0]) * .5
cur_yrange = (cur_ylim[1] - cur_ylim[0]) * .5
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
if event.button == 'up':
# deal with zoom in
scale_factor = 1 / base_scale
elif event.button == 'down':
# deal with zoom out
scale_factor = base_scale
else:
# deal with something that should never happen
scale_factor = 1
print(event.button)
# set new limits
ax.figure.canvas.toolbar.push_current() # resolve home button issue
# zoom for better user erxperince
ax.set_xlim([xdata - (xdata - cur_xlim[0]) / scale_factor,
xdata + (cur_xlim[1] - xdata) / scale_factor])
ax.set_ylim(
[ydata - (ydata - cur_ylim[0]) / scale_factor, ydata + (cur_ylim[1] - ydata) / scale_factor])
self.Canvas1.draw_idle()
fig = ax.get_figure() # get the figure of interest
# attach the call back
fig.canvas.mpl_connect('scroll_event', zoom_fun)
# return the function
return zoom_fun
这是放大之前的输出(图 1),这很好:
这是放大后的输出(图 2),我想剪辑在子图边界外以蓝色圆圈显示的文本:
解决方案
推荐阅读
- azure-synapse - Azure Synapse 中的 OPENJSON 排序规则导致排序规则冲突错误
- elasticsearch - Elasticsearch 返回字段中的命中数
- typescript - nextjs-auth 授权凭证类型记录
- reactjs - React 中带有加载进度条的文件上传(使用 RTK 查询)
- python - 提前停止 val_loss 未在 k 折交叉验证中重置
- python - 每次我从选项中点击配置 IDLE 时,Python 3.10 IDLE 都不响应
- javascript - React Light 代码编辑器与选项卡有问题
- django - 不使用 pip 更新 django
- reactjs - 如何更新 Seq 中的项目?
- css - css 属性注释中的感叹号导致它被识别为活动