使用python

时间:2017-11-29 08:53:46

标签: python numpy matplotlib scipy

当我只有一个已知的Y坐标方程,即P = a * b(其中a& b定义的值为0.8,150)和x坐标完全未知时,如何在曲线绘图上得到一个点并且没有关联x和y的等式(例如:y = mx + b;#我没有这种方程式)。所以,现在的目标就是说我有'Y'坐标'值为120并且需要通过从未知的&x-coordiante'中获取距离或路径来绘制曲线上的点。值。

我尝试了以下代码

One sample figure about how I should plot

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline

# given values
y = np.array([0, 38.39, 71.41, 99.66, 123.67, 143.88, 160.61, 174.03, 184.16, 190.8, 193.52])
x = np.array([0, 0.37, 0.74, 1.11, 1.48, 1.85, 2.22, 2.59, 2.96, 3.33, 3.7])
x_val = np.linspace(0,7) #limts on x-axis
a = 0.8
b = 150
y_val = np.multiply(a, b)
yinterp = np.interp(x_val, x, y)
plt.plot(x, y, '-')
plt.plot(x_val, yinterp, 'o')

#here i need to plot a exact point w.r.t to y_val
#and also need to show the distance with a line from the selected x and y coordinates

plt.plot(x_val,y_val, '--') 
plt.show()

1 个答案:

答案 0 :(得分:2)

你想要的是找到一个数组的根或零。这个问题的答案显示了如何做到这一点:How to get values from a graph?

将解决方案应用于此案例如下:

import matplotlib.pyplot as plt
import numpy as np

# given values
y = np.array([0, 38.39, 71.41, 99.66, 123.67, 143.88, 160.61, 174.03, 184.16, 190.8, 193.52])
x = np.array([0, 0.37, 0.74, 1.11, 1.48, 1.85, 2.22, 2.59, 2.96, 3.33, 3.7])
x_val = np.linspace(0,7) 

plt.plot(x, y, '-')

def find_roots(x,y):
    s = np.abs(np.diff(np.sign(y))).astype(bool)
    return x[:-1][s] + np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s])+1)

a = 0.8
b = 150
y_val = np.multiply(a, b)

roots = find_roots(x, y-y_val)
plt.plot(roots[0],y_val, marker="o") 
plt.plot([roots[0],roots[0],0],[0,y_val,y_val], "--")

plt.xlim(0,None)
plt.ylim(0,None)
plt.show()

enter image description here

如果数组单调递增,您当然也可以简单地插值:

import matplotlib.pyplot as plt
import numpy as np

# given values
y = np.array([0, 38.39, 71.41, 99.66, 123.67, 143.88, 160.61, 174.03, 184.16, 190.8, 193.52])
x = np.array([0, 0.37, 0.74, 1.11, 1.48, 1.85, 2.22, 2.59, 2.96, 3.33, 3.7])
x_val = np.linspace(0,7) 

plt.plot(x, y, '-')

a = 0.8
b = 150
y_val = np.multiply(a, b)

root = np.interp(y_val,y,x)
plt.plot(root,y_val, marker="o") 
plt.plot([root,root,0],[0,y_val,y_val], "--")

plt.xlim(0,None)
plt.ylim(0,None)
plt.show()