2015-12-01 32 views
14

matplotlibの線図に矢印を追加したいと考えています(pgfplotsで描画)。matplotlibを使用した線図の矢印

enter image description here

私は(矢印の位置と方向は、理想的なパラメータであるべき)方法を行うことができますか?

ここに実験するコードを示します。

from matplotlib import pyplot 
import numpy as np 

t = np.linspace(-2, 2, 100) 
plt.plot(t, np.sin(t)) 
plt.show() 

ありがとうございます。

答えて

8

これはannotateを使用して最高の作品。それによって、あなたは何とかコントロールするのが難しいax.arrowであなたが得る奇妙な歪みを避けます。

編集:私はそれを少しの機能に包んだ。

from matplotlib import pyplot as plt 
import numpy as np 


def add_arrow(line, position=None, direction='right', size=15, color=None): 
    """ 
    add an arrow to a line. 

    line:  Line2D object 
    position: x-position of the arrow. If None, mean of xdata is taken 
    direction: 'left' or 'right' 
    size:  size of the arrow in fontsize points 
    color:  if None, line color is taken. 
    """ 
    if color is None: 
     color = line.get_color() 

    xdata = line.get_xdata() 
    ydata = line.get_ydata() 

    if position is None: 
     position = xdata.mean() 
    # find closest index 
    start_ind = np.argmin(np.absolute(xdata - position)) 
    if direction == 'right': 
     end_ind = start_ind + 1 
    else: 
     end_ind = start_ind - 1 

    line.axes.annotate('', 
     xytext=(xdata[start_ind], ydata[start_ind]), 
     xy=(xdata[end_ind], ydata[end_ind]), 
     arrowprops=dict(arrowstyle="->", color=color), 
     size=size 
    ) 


t = np.linspace(-2, 2, 100) 
y = np.sin(t) 
# return the handle of the line 
line = plt.plot(t, y)[0] 

add_arrow(line) 

plt.show() 

これはあまり直感的ではありませんが、機能します。 arrowpropsディクショナリで正しく見えるようになるまで、それを練習することができます。

+0

いいアイデア。ありがとうございます(+1)。これを 'plot'の中に詰め込む方法はありませんか? – cjorssen

+0

あなた自身の 'plot'関数を書かない限り:)。これの利点は、注釈やテキストのようなものは、プロットするものよりもmatplotlibによって異なって扱われるということです。つまり、サイズを変更したりズームしたりするときに常にサイズやアスペクト比などを保持します。 – thomas

+0

意味をなさない – cjorssen

3

ない素敵なソリューションが、動作するはずです:私の経験で

import matplotlib.pyplot as plt 
import numpy as np 


def makeArrow(ax,pos,function,direction): 
    delta = 0.0001 if direction >= 0 else -0.0001 
    ax.arrow(pos,function(pos),pos+delta,function(pos+delta),head_width=0.05,head_length=0.1) 

fun = np.sin 
t = np.linspace(-2, 2, 100) 
ax = plt.axes() 
ax.plot(t, fun(t)) 
makeArrow(ax,0,fun,+1) 

plt.show() 
+0

ありがとうございました。 'プロット'に過度のチャンスはありませんか? – cjorssen

7

だけplt.arrow()を追加します。

from matplotlib import pyplot as plt 
import numpy as np 

# your function 
def f(t): return np.sin(t) 

t = np.linspace(-2, 2, 100) 
plt.plot(t, f(t)) 
plt.arrow(0, f(0), 0.01, f(0.01)-f(0), shape='full', lw=0, length_includes_head=True, head_width=.05) 
plt.show() 

はEDIT:描画する機能の位置&方向を含むように矢印の変更されたパラメータ。

enter image description here

+0

' np.sin'を 'np.cos'に変更すると、矢印の座標。私はそれを避けたいです。 @elzellの答えはより良いです。とにかくありがとう。 – cjorssen

+1

@cjorssen矢印の位置と方向を動的に計算する答えを変更しました。 – adrianus

+0

ありがとう、それは(+1)です。 – cjorssen

関連する問題