python – 如何在matplotlib的曲线末端放置一个箭头?

我想在曲线旁边的箭头.例如:

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(0,4*np.pi,10000)
Y = np.sin(X)

shift = 0.1
seg_size = 300

i = 0
plt.plot(X,Y,color='blue')
while i +seg_size < len(X):
    x = X[i:i+seg_size]
    y = Y[i:i+seg_size]+shift
    plt.plot(x,y,color='black')
    #input here command for arrow head
    i += seg_size*2

plt.show()

我试图计算曲线末端线下的角度并绘制箭头线,但我做错了,箭头变形了.任何提示?

最佳答案 FancyArrowPatch类将路径作为参数,所以我认为你可以使用它.

1)对于每个线段,创建一个matplotlib.path.Path实例.

2)使用路径实例绘制箭头.

import numpy as np
import matplotlib.pyplot as plt; plt.ion()
from matplotlib.patches import FancyArrowPatch, PathPatch
from matplotlib.path import Path

def create_path(x,y):
    vertices = zip(x,y)
    codes = [Path.MOVETO] + (len(vertices)-1) * [Path.CURVE3]
    return Path(vertices, codes)

X = np.linspace(0,4*np.pi,10000)
Y = np.sin(X)

fig, ax = plt.subplots(1,1)
ax.plot(X,Y,color='blue')

shift = 0.1
seg_size = 300

i = 0
while i +seg_size < len(X):
    x = X[i:i+seg_size]
    y = Y[i:i+seg_size]+shift

    path = create_path(x,y)

    # for testing path 
    # patch = PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)

    arrow = FancyArrowPatch(path=path, color='r')
    ax.add_artist(arrow)

    i += seg_size*2

不幸的是,这不起作用,因为传递给FancyArrowPatch的路径不能超过2个段(没有记录,但是在ensure_quadratic_bezier中有一个检查).

所以你必须作弊.下面我使用每个段的最后2个点来绘制箭头.

import numpy as np
import matplotlib.pyplot as plt; plt.ion()
from matplotlib.patches import FancyArrowPatch

X = np.linspace(0,4*np.pi,10000)
Y = np.sin(X)

fig, ax = plt.subplots(1,1)
ax.plot(X,Y,color='blue')

shift = 0.1
seg_size = 300

i = 0
while i +seg_size < len(X):
    x = X[i:i+seg_size]
    y = Y[i:i+seg_size]+shift

    ax.plot(x, y, 'k')

    posA, posB = zip(x[-2:], y[-2:])
    edge_width = 2.
    arrowstyle = "fancy,head_length={},head_width={},tail_width={}".format(2*edge_width, 3*edge_width, edge_width)
    arrow = FancyArrowPatch(posA=posA, posB=posB, arrowstyle=arrowstyle, color='k')
    ax.add_artist(arrow)

    i += seg_size*2

《python – 如何在matplotlib的曲线末端放置一个箭头?》

点赞