matplotlib:向图中添加指北针

kognpnkq  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(159)

我已经使用了以下代码将指北针添加到Map中:

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"))

字符串
输出如下:x1c 0d1x的数据
问题是我不能在轴的顶部画N和箭头。如果我把坐标弄乱了,我的代码就根本画不出N和箭头!我该如何解决此问题?
顺便说一句,有没有办法把N覆盖在箭头上?

ldxq2e6h

ldxq2e6h1#

用这个试试

def add_north_arrow(ax):

  py =0.8 * ax.figure.bbox.height
  px =0.05 * ax.figure.bbox.width

  # Draw an arrow with a text "N" above it using annotation
  ax.annotate("N", xy=(px, py), fontsize=20, xycoords="figure pixels")
  ax.annotate("",  xy=(px,  py), xytext=(px, py-30),xycoords="figure pixels",
          arrowprops=dict(arrowstyle="-|>", facecolor="black"))

字符串
P.S.
你得稍微调整一下尺寸和偏移量。我用这个测试了代码

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(nrows = 1, ncols =1)
ax.imshow(np.zeros((300, 300)))
add_north_arrow(ax)
plt.show()


的数据

相关问题