如何纠正ax.annotate中的坐标偏移

huangapple go评论63阅读模式
英文:

How to correct coordinate shifting in ax.annotate

问题

我尝试使用`ax.annotate`为折线图添加注释如下所示

    import numpy as np
    import matplotlib.pyplot as plt
    
    x_start = 0
    x_end = 200
    y_start = 20
    y_end = 20
    
    fig, ax = plt.subplots(figsize=(5,5),dpi=600)
    ax.plot(np.asarray([i for i in range(0,1000)]))
    ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
                arrowprops={'arrowstyle': '|-|'})
    plt.show()

这会生成一个放大的图表

虽然我已经指定了`x_start``0`,`x_end``200`,但实际上在x轴上实际的起始位置大于`0`,实际的结束位置小于`200`。

我该如何使这个注释正确对齐到设定的坐标上
英文:

I tried to annotate a line plot with ax.annotate as follows.

import numpy as np
import matplotlib.pyplot as plt

x_start = 0
x_end = 200
y_start = 20
y_end = 20

fig, ax = plt.subplots(figsize=(5,5),dpi=600)
ax.plot(np.asarray([i for i in range(0,1000)]))
ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|'})
plt.show()

which gave a plot (zoomed in)

如何纠正ax.annotate中的坐标偏移

Although I have specified x_start to be 0 and x_end to be 200, the actual start is greater than 0 and actual end is smaller than 200 on the x-axis.

How do I correctly line up this annotation with the set coordinates?

答案1

得分: 4

默认情况下,箭头在两端都缩小了2个点(请参阅文档)。您可以将shrinkAshrinkB设置为0,以与您的x轴对齐:

import numpy as np
import matplotlib.pyplot as plt

x_start = 0
x_end = 200
y_start = 20
y_end = 20

fig, ax = plt.subplots(figsize=(5,5),dpi=600)
ax.plot(np.asarray([i for i in range(0,1000)]))
ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|', 'shrinkA': 0, 'shrinkB': 0})
plt.show()

输出:

如何纠正ax.annotate中的坐标偏移

英文:

By default, the arrow is shrunk by 2 points on both ends (see the doc). You can set shrinkA and shrinkB to 0 to align with your x-axis:

import numpy as np
import matplotlib.pyplot as plt

x_start = 0
x_end = 200
y_start = 20
y_end = 20

fig, ax = plt.subplots(figsize=(5,5),dpi=600)
ax.plot(np.asarray([i for i in range(0,1000)]))
ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
            arrowprops={'arrowstyle': '|-|', 'shrinkA': 0, 'shrinkB': 0})
plt.show()

Output:

如何纠正ax.annotate中的坐标偏移

huangapple
  • 本文由 发表于 2023年6月29日 14:04:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定