英文:
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)
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个点(请参阅文档)。您可以将shrinkA
和shrinkB
设置为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()
输出:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论