python - python matplotlib:如何在只知道 x 值的曲线上添加点标记?
问题描述
例如,在 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 - 如何根据来自另一个 DataFrame 的列更新 pandas DataFrame 中的列
- laravel - 在 PackageManifest.php 第 177 行:
- assembly - 从汇编程序引用 C 指针
- python - Tensorflow Keras 不适用于参差不齐的张量输入
- javascript - 如何一一返回 rows 数组数据?
- python - AttributeError: 'Employee' 对象没有属性 'fullname' 以及 apply_raise()
- amazon-web-services - UNLOAD:集群中的切片是什么?
- python - Matplotlib:不可能在子图外的右 ytick 值上设置 0.0 和 1.0
- can-bus - CANopen 中是否有正式的归零方法
- sapui5 - SAP UI5 - 资源包