Jupyter 实验室绘图问题:`plt.scatter()` 工作得很好,但 `plt.plot()` 无法绘图

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

这里是 Jupyter Lab、Conda 和 Matplotlib 的新手。

所以我遇到了最奇怪的问题。

背景如下:我正在 Ubuntu 虚拟机上运行 Jupyter Lab。我的程序使用

polyfit()
找到一条最适合 30 个随机生成点的线。这些点是使用目标函数随机生成的。我首先使用了 1 阶的多重拟合线(只是一条线),然后使用了 3 阶的多重拟合线,以便使用随机生成的点更好地逼近目标函数。我生成了随机点、目标函数和两个 polyfit 函数,它们工作得很好,甚至在 Jupyter Lab 中进行了绘制。

问题在于:关闭我正在处理的 .ipynb 文件后。我使用 Ubuntu 的文件资源管理器重新打开它(当 Jupyter Lab 实例仍在运行时)。我对程序做了一些更改,现在它不再绘图了。

plt.scatter()
仍然可以很好地绘制散点图,但是
plt.plot()
不会在我的图表上显示函数。我没有收到任何类型的警告消息或任何解释器错误。现在,我可以看到两个可能的原因:

  1. 当我关闭 .ipynb 文件并在文件资源管理器中重新打开它而 Jupyter Lab 实例仍在运行时,我搞砸了一些东西。一些人在这里闲逛发现其他用户也有隐约类似的问题,并且问题是由于环境不再链接而引起的?我检查过,我的(基本)Conda 环境已安装 matplotlib。这可能是也可能不是原因,但我认为值得一提的是帮助排除故障。

  2. 第二个也是更常见的原因是我只是把程序中的一些东西弄乱了(我是Python的相对初学者,所以这完全有可能)。我尝试自己调试该程序,但没有警告或错误消息,很难知道从哪里开始。我的

    print()
    语句显示变量的类型正确(数组/列表或浮点数)。

这是我的程序(它是一个 .ipynb 文件)。非常感谢所有有用的建议。谢谢!

import numpy as np
import matplotlib.pyplot as plt
import random
import warnings

# warnings.filterwarnings("ignore")

def func(x): 
    return x**3 + 2 * x**2 - 5 * x - 6

def line(x):
    return slope * x + y_int

def third_poly(x):
    return poly_trans[0] * x**3 + poly_trans[1] * x**2 + poly_trans[2] * x + poly_trans[3]

num_of_data_points = 30

x = np.linspace(-4.0, 4.0)
x_values = []
y_values = []

for i in range(num_of_data_points):
    x = np.random.uniform(-4.0, 4.0)
    y = np.random.uniform(-2.0, 2.0)
    fx = func(x) + y
    plt.scatter(x, fx)
    x_values.append(x)
    y_values.append(fx)

lin_reg = np.polyfit(x_values, y_values, 1)
# lin_reg is an array of size 1x2, first element is the coefficient, second element is the y-int

poly_trans = np.polyfit(x_values, y_values, 3)

print(lin_reg)
print(lin_reg.shape)

print(poly_trans)
print(poly_trans.shape)

y_int = lin_reg.flat[1]
slope = np.delete(lin_reg, 1)

print(y_int)
print(y_int.shape)
print(slope)
print(slope.shape)

plt.plot(x, func(x), label = "Target function (f(x))")
plt.plot(x, line(x), label = "Line of best fit (g)")
plt.plot(x, third_poly(x), label = "3rd-Order Polynomial transformation (g')")
plt.legend(loc = "upper left")
plt.ylim(-45, 50)
plt.xlim(-5, 5)
plt.grid()
plt.show()

这是输出:

python matplotlib ubuntu virtual-machine jupyter-lab
1个回答
0
投票

您有一个小的语义错误,您正在绘制相对于单个数据点

x
的函数。您应该用
x_values
绘制它们。此外,for 循环内的绘图会适得其反,因为这会将每个新的散点图视为一个新组(因此有不同的颜色)。

这是一个更好的版本:

# Define the target function
def targetFunction(x):  # Define the target function f(x)
    return x**3 + 2 * x**2 - 5 * x - 6

# Define the line function
def lineFunction(x, slope, yIntercept):  # Define the line function g(x)
    return slope * x + yIntercept

# Define the third degree polynomial function
def thirdPolyFunction(x, polyTransform):  # Define the 3rd degree polynomial function g'(x)
    return polyTransform[0] * x**3 + polyTransform[1] * x**2 + polyTransform[2] * x + polyTransform[3]

# Generating data points
numOfDataPoints = 30
xValues = []  # Initialize list to store x values
yValues = []  # Initialize list to store y values
for i in range(numOfDataPoints):  # Loop for generating random data points
    x = np.random.uniform(-4.0, 4.0)  # Generate random x value within range
    y = np.random.uniform(-2.0, 2.0)  # Generate random y value within range
    fx = targetFunction(x) + y  # Compute y value based on target function and random noise
    xValues.append(x)  # Append x value to the list
    yValues.append(fx)  # Append y value to the list

# Regression and sorting
linReg = np.polyfit(xValues, yValues, 1)  # Perform linear regression
yIntercept = linReg[1]  # Extract y-intercept from linear regression
slope = linReg[0]  # Extract slope from linear regression
polyTransform = np.polyfit(xValues, yValues, 3)  # Perform polynomial transformation
sortedIndices = np.argsort(xValues)  # Get indices that would sort the x values
sortedX = np.array(xValues)[sortedIndices]  # Sort x values in ascending order
sortedY = np.array(yValues)[sortedIndices]  # Sort y values corresponding to sorted x values

# Plotting
plt.figure()
plt.scatter(sortedX, sortedY)  # Plot the sorted data points
plt.plot(sortedX, targetFunction(sortedX), label="Target function f(x)")  # Plot the target function
plt.plot(sortedX, lineFunction(sortedX, slope, yIntercept), label="Line of best fit (g)")  # Plot the line of best fit
plt.plot(sortedX, thirdPolyFunction(sortedX, polyTransform), label="3rd-Order Polynomial transformation (g')")  # Plot the polynomial transformation
plt.legend(loc="upper left")  # Add legend to the plot
plt.ylim(-45, 50)  # Set y-axis limits
plt.xlim(-5, 5)  # Set x-axis limits
plt.grid()  # Add grid lines to the plot
plt.title("Data Points, Target Function, and Fitted Models")  # Add title to the plot

另外,我可以推荐使用以下导入:

import numpy as np
%matplotlib notebook
import matplotlib.pyplot as plt

%matplotlib notebook
非常好,因为它支持交互式绘图。希望这有帮助!

结果:

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