技术制图中距离箭头的绘制

2024-09-27 07:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的一个图中标出一个距离。我想的是他们在技术图纸上的做法,显示了一个双头箭头,旁边的文字是距离。

示例:

from matplotlib.pyplot import *

hlines(7,0,2, linestyles='dashed')
hlines(11,0,2, linestyles='dashed')
hlines(10,0,2, linestyles='dashed')
hlines(8,0,2, linestyles='dashed')
plot((1,1),(8,10), 'k',) # arrow line
plot((1,1),(8,8), 'k', marker='v',) # lower arrowhead
plot((1,1),(10,10), 'k', marker='^',) # upper arrowhead
text(1.1,9,"D=1")

结果是这样的(两个hline不是真的需要,它们只是增加了绘图区域…):Distance marker manual style

有没有一种更快的方法可以做到这一点,最好是箭头在正确的地方结束,而不是下面/上面他们应该在哪里? 用于自动放置文本的额外点。

编辑: 我一直在玩annotate,但是由于必须牺牲字符串,这个解决方案对我失去了一些吸引力。不过,谢谢你指出箭头的样式,当我尝试类似的东西时,它不起作用。 我想没有办法用一个调用来编写一个小函数。。。


Tags: from距离示例plotmatplotlib箭头marker技术
3条回答
import matplotlib.pyplot as plt

plt.hlines(7, 0, 2, linestyles='dashed')
plt.hlines(11, 0, 2, linestyles='dashed')
plt.hlines(10, 0, 2, linestyles='dashed')
plt.hlines(8, 0, 2, linestyles='dashed')
plt.annotate(
    '', xy=(1, 10), xycoords='data',
    xytext=(1, 8), textcoords='data',
    arrowprops={'arrowstyle': '<->'})
plt.annotate(
    'D = 1', xy=(1, 9), xycoords='data',
    xytext=(5, 0), textcoords='offset points')

# alternatively,
# plt.text(1.01, 9, 'D = 1')

plt.show()

收益率

enter image description here

有关plt.annotate提供的许多选项的详细信息,请参见this page


如上所示,文本可以用plt.annotateplt.text放置。使用plt.annotate可以在点中指定偏移量(例如(5, 0)),而使用plt.text可以在数据坐标中指定文本位置(例如(1.01, 9))。

我已经设计了一个函数来很好地实现这一点:

import numpy as np
import matplotlib.pyplot as plt

def annotate_point_pair(ax, text, xy_start, xy_end, xycoords='data', text_offset=6, arrowprops = None):
    """
    Annotates two points by connecting them with an arrow. 
    The annotation text is placed near the center of the arrow.
    """

    if arrowprops is None:
        arrowprops = dict(arrowstyle= '<->')

    assert isinstance(text,str)

    xy_text = ((xy_start[0] + xy_end[0])/2. , (xy_start[1] + xy_end[1])/2.)
    arrow_vector = xy_end[0]-xy_start[0] + (xy_end[1] - xy_start[1]) * 1j
    arrow_angle = np.angle(arrow_vector)
    text_angle = arrow_angle - 0.5*np.pi

    ax.annotate(
            '', xy=xy_end, xycoords=xycoords,
            xytext=xy_start, textcoords=xycoords,
            arrowprops=arrowprops)

    label = ax.annotate(
        text, 
        xy=xy_text, 
        xycoords=xycoords,
        xytext=(text_offset * np.cos(text_angle), text_offset * np.sin(text_angle)), 
        textcoords='offset points')

    return label

尝试使用annotate

annotate ('', (0.4, 0.2), (0.4, 0.8), arrowprops={'arrowstyle':'<->'})

Image produced by annotate command

但我不确定自动文本放置。

相关问题 更多 >

    热门问题