Python 如何在cartopy地图上缩放时剪裁子地块边界外的文本?
我使用带有cartopy包的matplotlib在matplotlib图的子图中显示巴基斯坦地图及其城市名称,如图1所示。 但我的问题是,当我放大子地块以查看更多细节时,一切正常,但绘制的文本(城市名称)显示在子地块边界之外,如何剪裁外部文本 这是我在卡通地图上绘制城市名称的代码Python 如何在cartopy地图上缩放时剪裁子地块边界外的文本?,python,matplotlib,data-visualization,cartopy,Python,Matplotlib,Data Visualization,Cartopy,我使用带有cartopy包的matplotlib在matplotlib图的子图中显示巴基斯坦地图及其城市名称,如图1所示。 但我的问题是,当我放大子地块以查看更多细节时,一切正常,但绘制的文本(城市名称)显示在子地块边界之外,如何剪裁外部文本 这是我在卡通地图上绘制城市名称的代码 def draw_cities(self, extent, axis): cities_df = pd.read_csv('assets/maps/cities.csv')
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)
这是放大前的输出(图1),放大效果良好:
这是放大后的输出(图2),我想剪辑子地块边界外以蓝色圆圈显示的文本:
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