我正在尝试将文本标记中的线条渲染到其原始位置。复杂的是我是从 Cartopy 做这件事的。我的代码如下所示:-
# Set up the figure and axis
tiler = OrdnanceSurvey(os_maps_key, layer=kwargs.get('layer', 'Road_3857'))
tile_crs = tiler.crs
fig = plt.figure(figsize=(8.27, 5.845))
plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
ax = fig.add_subplot(1, 1, 1, projection=tile_crs)
ax.set_extent([bbox[0], bbox[2], bbox[1], bbox[3]], crs=ccrs.Geodetic())
ax.add_image(tiler, zoom_level)
# Iterate through a data frame pts to add markers and text
texts=[]
for x, y, icon_name, sequence in zip(pts.geometry.x, pts.geometry.y, pts['icon'], pts['sequence']):
# text labels
text = ax.text(x, y, int(sequence),
bbox={'facecolor': 'none', 'edgecolor': 'none', 'pad': 0},
fontsize=12,
ha='center', va='center',
color='black',
transform=ccrs.Geodetic())
texts.append(text)
# markers
ax.plot(x, y, marker='o', markersize=5, color='blue', transform=ccrs.Geodetic())
# adjust the text labels to remove overlap
adjust_text(texts,
ax=ax,
expand=(4, 2),
arrowprops=dict(arrowstyle='simple', color='blue', lw=1)
)
渲染文本和标记,但不渲染由 adjustment_text 添加的 FancyArrowPatch 元素。我尝试过传递相同的转换,但这没有效果。
我已经调试了代码,可以看到 adjustment_text 正在创建补丁并使用 ax.add_patch 将它们添加到 ax 中。它们似乎具有不同的开始和结束坐标,因此看起来它们正在被创建。
我怎样才能弄清楚它们不渲染的原因?我尝试过的其他事情是:-
这些都不起作用。
调试并查看转换似乎不匹配:-
arrowpatch
Out[6]: <matplotlib.patches.FancyArrowPatch at 0x162cc8d10>
arrowpatch.get_transform()
Out[7]: <matplotlib.transforms.IdentityTransform at 0x163439e50>
text.get_transform()
Out[8]: <matplotlib.transforms.CompositeGenericTransform at 0x162c8b190>
但是将transform=ccrs.Geodetic()添加到arrowprops会出现错误“AttributeError:'Geodetic'对象没有属性'quick_vertices_transform'”
我找到了一个解决方案,它并不理想,但 FancyArrowPatch 不能很好地处理传递给它的 Cartopy 变换。解决方案是在 adjustment_text 之外添加箭头:-
original_texts = copy.deepcopy(texts)
adjust_text(texts,
ax=ax,
expand=(4, 2))
for original, moved in zip(original_texts,texts):
start_proj = tile_crs.transform_point(*original.get_position(), src_crs=ccrs.Geodetic())
end_proj = tile_crs.transform_point(*moved.get_position(), src_crs=ccrs.Geodetic())
arrow = FancyArrowPatch(posA=start_proj, posB=end_proj,
arrowstyle='-', mutation_scale=20, lw=0.5, color='blue')
ax.add_patch(arrow)