Python 带箭头记号的Matplotlib曲线
我想知道是否可以在Python 带箭头记号的Matplotlib曲线,python,matplotlib,plot,Python,Matplotlib,Plot,我想知道是否可以在matplotlib中用箭头标记绘制曲线 比如: from pylab import * y = linspace(0,10,0.01) x = cos(y) plot(x, y, '->') 当x增加时,会产生这样的曲线 import numpy as np import matplotlib.pyplot as plt y = np.linspace(0,100,100) x = np.cos(y/5.) # use masked arrays x1 = n
matplotlib
中用箭头标记绘制曲线
比如:
from pylab import *
y = linspace(0,10,0.01)
x = cos(y)
plot(x, y, '->')
当x增加时,会产生这样的曲线
import numpy as np
import matplotlib.pyplot as plt
y = np.linspace(0,100,100)
x = np.cos(y/5.)
# use masked arrays
x1 = np.ma.masked_array(x[:-1], np.diff(x)>=0)
x2 = np.ma.masked_array(x[:-1], np.diff(x)<=0)
# print the line and the markers in seperate steps
plt.plot(x, y, 'k-')
plt.plot(x1, y[:-1], 'k<')
plt.plot(x2, y[:-1], 'k>')
plt.show()
将numpy导入为np
将matplotlib.pyplot作为plt导入
y=np.linspace(0100)
x=np.cos(y/5)
#使用屏蔽数组
x1=np.ma.屏蔽_数组(x[:-1],np.diff(x)>=0)
x2=np.ma.屏蔽_数组(x[:-1],np.diff(x)可以使用与matplotlibstreamplot
函数相同的策略。基于hitzg已经给出的示例:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
def add_arrow_to_line2D(
axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8],
arrowstyle='-|>', arrowsize=1, transform=None):
"""
Add arrows to a matplotlib.lines.Line2D at selected locations.
Parameters:
-----------
axes:
line: Line2D object as returned by plot command
arrow_locs: list of locations where to insert arrows, % of total length
arrowstyle: style of the arrow
arrowsize: size of the arrow
transform: a matplotlib transform instance, default to data coordinates
Returns:
--------
arrows: list of arrows
"""
if not isinstance(line, mlines.Line2D):
raise ValueError("expected a matplotlib.lines.Line2D object")
x, y = line.get_xdata(), line.get_ydata()
arrow_kw = {
"arrowstyle": arrowstyle,
"mutation_scale": 10 * arrowsize,
}
color = line.get_color()
use_multicolor_lines = isinstance(color, np.ndarray)
if use_multicolor_lines:
raise NotImplementedError("multicolor lines not supported")
else:
arrow_kw['color'] = color
linewidth = line.get_linewidth()
if isinstance(linewidth, np.ndarray):
raise NotImplementedError("multiwidth lines not supported")
else:
arrow_kw['linewidth'] = linewidth
if transform is None:
transform = axes.transData
arrows = []
for loc in arrow_locs:
s = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
n = np.searchsorted(s, s[-1] * loc)
arrow_tail = (x[n], y[n])
arrow_head = (np.mean(x[n:n + 2]), np.mean(y[n:n + 2]))
p = mpatches.FancyArrowPatch(
arrow_tail, arrow_head, transform=transform,
**arrow_kw)
axes.add_patch(p)
arrows.append(p)
return arrows
y = np.linspace(0, 100, 200)
x = np.cos(y/5.)
fig, ax = plt.subplots(1, 1)
# print the line and the markers in seperate steps
line, = ax.plot(x, y, 'k-')
add_arrow_to_line2D(ax, line, arrow_locs=np.linspace(0., 1., 200),
arrowstyle='->')
plt.show()
另请参阅。我已经做了第一次尝试,并为您提供了一个工作示例。您自己尝试过任何东西吗?这非常有效!谢谢!3D绘图是否可以使用类似的方法?简单的解决方案非常有效!