本文介绍了使用matplotlib绘制线图中的箭头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在matplotlib的线图中添加箭头,如下图所示(用 pgfplots ).

I'd like to add an arrow to a line plot with matplotlib like in the plot below (drawn with pgfplots).

我该怎么做(理想情况下,箭头的位置和方向应该是参数)?

How can I do (position and direction of the arrow should be parameters ideally)?

这是一些要实验的代码.

Here is some code to experiment.

from matplotlib import pyplot
import numpy as np

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

谢谢.

推荐答案

以我的经验,使用注释.这样就避免了ax.arrow带来的怪异扭曲,这在某种程度上很难控制.

In my experience this works best by using annotate. Thereby you avoid the weird warping you get with ax.arrow which is somehow hard to control.

编辑:我将其包装为一个小功能.

I've wrapped it into a little function.

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字典,直到看起来正确为止.

It's not very intuitive but it works. You can then fiddle with the arrowprops dictionary until it looks right.

这篇关于使用matplotlib绘制线图中的箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:59