突出显示 matplotlib 图中的任意点? [英] Highlighting arbitrary points in a matplotlib plot?
问题描述
我是 python 和 matplotlib 的新手.
我试图在 matplotlib 中的现有图中突出显示符合特定条件的几个点.
初始图的代码如下:
pl.plot(t,y)pl.title('阻尼正弦波,频率为 %.1f Hz' % f)pl.xlabel('t (s)')pl.ylabel('y')pl.grid()pl.show()
在上面的情节中,我想强调一些符合标准abs(y)> 0.5的特定点.提出这些要点的代码如下:
markers_on = [x for x in y if abs(x)>0.5]
我尝试使用参数'markevery',但抛出错误
'markevery' 是可迭代的,但不是 numpy 花式索引的有效形式;
给出错误的代码如下:
pl.plot(t,y,'-gD',markevery =markers_on)pl.title('具有%.1f Hz频率的阻尼正弦波'%f)pl.xlabel('t(s)')pl.ylabel('y')pl.grid()pl.show()
绘图函数的 markevery
参数接受不同类型的输入.根据输入类型,它们的解释不同.在
I am new to python and matplotlib.
I am trying to highlight a few points that match a certain criteria in an already existing plot in matplotlib.
The code for the initial plot is as below:
pl.plot(t,y)
pl.title('Damped Sine Wave with %.1f Hz frequency' % f)
pl.xlabel('t (s)')
pl.ylabel('y')
pl.grid()
pl.show()
In the above plot I wanted to highlight some specific points which match the criteria abs(y)>0.5. The code coming up with the points is as below:
markers_on = [x for x in y if abs(x)>0.5]
I tried using the argument 'markevery', but it throws an error saying
'markevery' is iterable but not a valid form of numpy fancy indexing;
The code that was giving the error is as below:
pl.plot(t,y,'-gD',markevery = markers_on)
pl.title('Damped Sine Wave with %.1f Hz frequency' % f)
pl.xlabel('t (s)')
pl.ylabel('y')
pl.grid()
pl.show()
The markevery
argument to the plotting function accepts different types of inputs. Depending on the input type, they are interpreted differently. Find a nice list of possibilities in this matplotlib example.
In the case where you have a condition for the markers to show, there are two options. Assuming t
and y
are numpy arrays and one has import
ed numpy as np
,
Either specify a boolean array,
plt.plot(t,y,'-gD',markevery = np.where(y > 0.5, True, False))
or
an array of indices.
plt.plot(t,y,'-gD',markevery = np.arange(len(t))[y > 0.5])
Complete example
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)
t = np.linspace(0,3,14)
y = np.random.rand(len(t))
plt.plot(t,y,'-gD',markevery = np.where(y > 0.5, True, False))
# or
#plt.plot(t,y,'-gD',markevery = np.arange(len(t))[y > 0.5])
plt.xlabel('t (s)')
plt.ylabel('y')
plt.show()
resulting in
这篇关于突出显示 matplotlib 图中的任意点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!