Matplotlib中地图顶部添加指北针及N文本叠加问题求解
地图指北针绘制问题
我用以下代码给地图添加指北针:
def add_north_arrow(ax): # Define the coordinates and dimensions of the arrow in display space x_tail = 0.05 * ax.figure.bbox.width # 5% of the figure width from the left y_tail = 0.05 * ax.figure.bbox.height # 5% of the figure height from the bottom dx = 0 # No horizontal displacement dy = 0.05 * ax.figure.bbox.height # 10% of the figure height vertical displacement # Draw an arrow with a text "N" above it using annotation ax.annotate("N", xy=(x_tail + dx/2, y_tail + dy + dy/10), xycoords="figure pixels", ha="center", va="center", fontsize=20) ax.annotate("", xy=(x_tail + dx, y_tail + dy), xycoords="figure pixels", xytext=(x_tail, y_tail), textcoords="figure pixels", arrowprops=dict(arrowstyle="-|>", facecolor="black"))
遇到两个问题:
- 无法将N文本与箭头绘制在坐标轴顶部,调整坐标后元素完全不显示
- 是否可以将N文本叠加在箭头上?
解决方案
1. 把指北针移到坐标轴顶部
你当前用figure pixels作为坐标系统,一旦y值超过figure的实际像素高度,元素就会被裁剪消失。改用**归一化坐标(figure fraction)**更可靠,它的取值范围是0-1,(0,0)对应figure左下角,(1,1)对应右上角,不管figure尺寸怎么变,位置都能稳定固定。
修改后的代码:
def add_north_arrow(ax): # 归一化坐标:0-1对应figure的宽高比例 x_tail = 0.05 # 距离左侧5%的位置 y_tail = 0.9 # 距离底部90%(靠近顶部) dy = 0.08 # 箭头长度占figure高度的8% # 绘制箭头 ax.annotate("", xy=(x_tail, y_tail + dy), # 箭头头部位置 xycoords="figure fraction", xytext=(x_tail, y_tail), # 箭头尾部位置 textcoords="figure fraction", arrowprops=dict(arrowstyle="-|>", facecolor="black")) # 绘制N文本(箭头头部上方) ax.annotate("N", xy=(x_tail, y_tail + dy + 0.02), xycoords="figure fraction", ha="center", va="center", fontsize=20)
调整y_tail的值就能控制指北针在顶部的具体位置,比如设为0.95就是更靠近顶部的区域,不会出现元素消失的问题。
2. 将N文本叠加在箭头上
只要让文本的坐标和箭头头部对齐,同时设置文本的zorder比箭头高,就能实现叠加效果(zorder值越大,图层越靠上)。代码如下:
def add_north_arrow(ax): x_tail = 0.05 y_tail = 0.9 dy = 0.08 # 先画箭头,zorder设为1(确保在文本下方) ax.annotate("", xy=(x_tail, y_tail + dy), xycoords="figure fraction", xytext=(x_tail, y_tail), textcoords="figure fraction", arrowprops=dict(arrowstyle="-|>", facecolor="black", zorder=1)) # 再画N文本,坐标与箭头头部一致,zorder设为2(在箭头上方) ax.annotate("N", xy=(x_tail, y_tail + dy), xycoords="figure fraction", ha="center", va="center", fontsize=20, zorder=2)
如果觉得重叠太紧密,可以微调文本的y坐标(比如y_tail + dy + 0.005),让它稍微偏上一点,既保持叠加感又不会完全挡住箭头。
内容的提问来源于stack exchange,提问作者SupernovifieD
相关产品推荐
相关产品推荐

