python matplotlib : How can I add a point mark to curve knowing only the x value?

标签 python matplotlib

例如,在 matplotlib 中,我根据几个点绘制一条简单的曲线:

from matplotlib import pyplot as plt
import numpy as np

x=[0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,
       1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,
       2.6, 2.7, 2.8, 2.9]
y=[0.0, 0.19, 0.36, 0.51, 0.64, 0.75, 0.8400000000000001, 0.91, 0.96, 0.99, 1.0, 
   0.99, 0.96, 0.9099999999999999, 0.8399999999999999, 0.75, 0.6399999999999997, 
   0.5099999999999998, 0.3599999999999999, 0.18999999999999995, 0.0, 
   -0.20999999999999996, -0.4400000000000004, -0.6900000000000004, 
   -0.9600000000000009, -1.25, -1.5600000000000005, -1.8900000000000006, 
   -2.240000000000001, -2.610000000000001]

plt.plot(x,y)
plt.show()

假设我想突出显示曲线上 x 值为 0.25 的点,但我不知道该点的 y 值。我该怎么办?

最佳答案

最简单的解决方案是在相邻点之间针对提供的 x 值执行线性插值。下面是一个示例代码来展示一般原理:

X=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2,
   1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,
   2.6, 2.7, 2.8, 2.9]
Y=[0.0, 0.19, 0.36, 0.51, 0.64, 0.75, 0.8400000000000001, 0.91, 0.96,
   0.99, 1.0, 0.99, 0.96, 0.9099999999999999, 0.8399999999999999, 0.75,
   0.6399999999999997, 0.5099999999999998, 0.3599999999999999,
   0.18999999999999995, 0.0, -0.20999999999999996, -0.4400000000000004,
   -0.6900000000000004, -0.9600000000000009, -1.25, -1.5600000000000005,
   -1.8900000000000006, -2.240000000000001, -2.610000000000001]

def interpolate(X, Y, xval):
    for n, x in enumerate(X):
        if x > xval: break
    else: return None # xval > last x value
    if n == 0: return None # xval < first x value
    xa, xb = X[n-1], X[n] # get surrounding x values
    ya, yb = Y[n-1], Y[n] # get surrounding y values
    if xb == xa: return ya # 
    return ya + (xval - xa) * (yb - ya) / (xb - xa) # compute yval by interpolation

print(interpolate(X, Y, 0.25)) # --> 0.435 
print(interpolate(X, Y, 0.85)) # --> 0.975
print(interpolate(X, Y, 2.15)) # --> -0.3259999999999997
print(interpolate(X, Y, -1.0)) # --> None (out of bounds)
print(interpolate(X, Y, 3.33)) # --> None (out of bounds)

注意:当提供的xval不在x值范围内时,函数返回None

关于python matplotlib : How can I add a point mark to curve knowing only the x value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513325/

相关文章:

python - 如何更改 Pandas 中分组条形图的颜色?

python - matplotlib x 标签放置

python - swarmplot 上方的 seaborn 点图

python - 带星号的参数的类型提示

Python:for语句行为

python - 没有可用的用户状态上下文谷歌云数据流?

python - 在 matplotlib 中更新 ConnectionPatch 的位置

python - 填充3D绘图Python

python - 在 Python 中表示二维网格的最有效方法

python 3.2 : How to setup versioning for a project