平面最佳拟合仅给出散点图上的抛物线?

问题描述 投票:0回答:1

我在 3 个轴上将一堆数据绘制为散点图。 我使用了一种方法并得到了抛物线形状,这不是我想要的,但给出的示例显示了独特的平面形状。我想我很困惑/不知道如何正确诊断我的问题是什么,因为查找和更改方程只会破坏笔记本。

下面代码中的

temp
x,y,z
基本上就是数据了。

def func(xy, a, b, c, d, e, f): 
    x, y = xy 
    return a + b*x + c*y + d*x**2 + e*y**2 + f*x*y

x = temp[xStr].to_numpy()
y = temp[yStr].to_numpy()
z = temp[zStr].to_numpy()

popt, pcov = curve_fit(func, (x, y), z) 

fig = plt.figure(figsize = (16, 9))
ax = fig.add_subplot(111, projection='3d') 

ax.set_xlim(0.15, 0.55)
ax.set_ylim(0, 35)
ax.set_zlim(60, 95)


x_range = np.linspace(0, 1, 50) 
y_range = np.linspace(0, 1, 50)

X, Y = np.meshgrid(x_range, y_range) 
Z = func((X, Y), *popt) 

ax.plot_surface(X, Y, Z, color='red', alpha=1) 
 

my_cmap = plt.get_cmap('cool')
 

sctt = ax.scatter3D(x, y, z,
                    alpha = 0.8,
                    c = (z), 
                    cmap = my_cmap, 
                    marker ='^')
 
plt.title("Line " + str(arg1))
ax.set_xlabel('Head CU', fontweight ='bold') 
ax.set_ylabel('ASCU', fontweight ='bold') 
ax.set_zlabel('Recovery', fontweight ='bold')
fig.colorbar(sctt, ax = ax, shrink = 0.5, aspect = 5)

当绘制这个图时,我得到了一条非常明显的红色抛物线。我怎样才能买到飞机?

parabola image

python pandas matplotlib jupyter-notebook
1个回答
0
投票

您的代码有两个主要问题。

首先,平面方程在 x 和 y 上应该是线性的(如评论中已经指出的)。你只需要

def func(xy, a, b, c): 
    x, y = xy 
    return a + b*x + c*y

其次,你绘制的曲面,无论是抛物面还是平面都只是为了

x_range = np.linspace(0, 1, 50) 
y_range = np.linspace(0, 1, 50)

特别是 0-1 的 y_range 与您为 y_lim 设置的限制(即 0-35)没有相似之处。因此,您正在绘制一个曲面,但它看起来更像是一条线,因为它只覆盖了图中 y 范围的大约 3%。

我在下面修改后的代码中弥补了一些数据(因为你没有提供)。飞机显然已经安装好了。您可以从

a
中的值得到
b
c
popt

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


def func(xy, a, b, c): 
    x, y = xy 
    return a + b*x + c*y

x = np.array( [ 0.2, 0.25, 0.20, 0.3, 0.30, 0.35, 0.45, 0.50, 0.50 ] )
y = np.array( [ 2.0, 20.0, 30.0, 3.0, 30.0, 35.0, 15.0, 18.0, 20.0 ] )
z = 60 + 15 * x + 0.6 * y

popt, pcov = curve_fit(func, (x, y), z)
print( "a, b, c=", popt ) 

xmin, xmax, ymin, ymax, zmin, zmax = 0.15, 0.55, 0.0, 35.0, 60.0, 95.0
x_range = np.linspace(xmin, xmax, 50)
y_range = np.linspace(ymin, ymax, 50)
X, Y = np.meshgrid(x_range, y_range) 
Z = func((X,Y), *popt)


fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111, projection='3d') 
ax.set_xlim(xmin,xmax)
ax.set_ylim(ymin,ymax)
ax.set_zlim(zmin,zmax)
ax.plot_surface(X, Y, Z, color='red', alpha=0.2)
my_cmap = plt.get_cmap('cool')
sctt = ax.scatter3D(x, y, z, alpha=0.8, c=(z), cmap=my_cmap, marker='^')
ax.set_xlabel('Head CU', fontweight ='bold') 
ax.set_ylabel('ASCU', fontweight ='bold') 
ax.set_zlabel('Recovery', fontweight ='bold')
fig.colorbar(sctt, ax = ax, shrink = 0.5, aspect = 5)
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.