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

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

How to correct coordinate shifting in ax.annotate

问题

  1. 我尝试使用`ax.annotate`为折线图添加注释如下所示
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. x_start = 0
  5. x_end = 200
  6. y_start = 20
  7. y_end = 20
  8. fig, ax = plt.subplots(figsize=(5,5),dpi=600)
  9. ax.plot(np.asarray([i for i in range(0,1000)]))
  10. ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
  11. arrowprops={'arrowstyle': '|-|'})
  12. plt.show()
  13. 这会生成一个放大的图表
  14. 虽然我已经指定了`x_start``0``x_end``200`但实际上在x轴上实际的起始位置大于`0`实际的结束位置小于`200`
  15. 我该如何使这个注释正确对齐到设定的坐标上
英文:

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

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x_start = 0
  4. x_end = 200
  5. y_start = 20
  6. y_end = 20
  7. fig, ax = plt.subplots(figsize=(5,5),dpi=600)
  8. ax.plot(np.asarray([i for i in range(0,1000)]))
  9. ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
  10. arrowprops={'arrowstyle': '|-|'})
  11. 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轴对齐:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x_start = 0
  4. x_end = 200
  5. y_start = 20
  6. y_end = 20
  7. fig, ax = plt.subplots(figsize=(5,5),dpi=600)
  8. ax.plot(np.asarray([i for i in range(0,1000)]))
  9. ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
  10. arrowprops={'arrowstyle': '|-|', 'shrinkA': 0, 'shrinkB': 0})
  11. 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:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. x_start = 0
  4. x_end = 200
  5. y_start = 20
  6. y_end = 20
  7. fig, ax = plt.subplots(figsize=(5,5),dpi=600)
  8. ax.plot(np.asarray([i for i in range(0,1000)]))
  9. ax.annotate('', xy=(x_start, y_start), xytext=(x_end, y_end), xycoords='data', textcoords='data',
  10. arrowprops={'arrowstyle': '|-|', 'shrinkA': 0, 'shrinkB': 0})
  11. 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:

确定