我想要一条曲线旁边的箭头。例如:
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()
我试着计算曲线末端的线下一个角度并绘制箭头线,但我做错了,箭头变形了。任何提示?
答案 0 :(得分:1)
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
答案 1 :(得分:0)
如何使用
numpy.annotate()
功能
请参阅pyplot.annotate()函数创建的箭头示例:
https://matplotlib.org/examples/pylab_examples/annotation_demo.html