如果x满足条件,如何在Python中绘制x-y数据

12 投票
1 回答
53548 浏览
提问于 2025-04-17 15:21

我想对一组x-y数据进行绘图或拟合,但前提是这组数据的x值要满足一个条件(也就是说,x值要大于10)。

我尝试过:

x_values, y_values = loadtxt(fname, unpack=True, usecols=[1, 0])

for x in x_values:
    if x > 10:
        (m,b)=polyfit(x_values,y_values,1)
        yp = polyval([m,b],x_values)
        plot(x_values,yp)
        scatter(x_values,y_values)
    else:
        pass

也许更好的办法是把那些x值不满足条件的行去掉,然后再进行绘图或拟合?

1 个回答

22

当然,可以使用布尔索引。你可以这样做,比如 y = y[x > 10]

例如:

import numpy as np
import matplotlib.pyplot as plt

#-- Generate some data...-------
x = np.linspace(-10, 50, 100)
y = x**2 + 3*x + 8

# Add a lot of noise to part of the data...
y[x < 10] += np.random.random(sum(x < 10)) * 300

# Now let's extract only the part of the data we're interested in...
x_filt = x[x > 10]
y_filt = y[x > 10]

# And fit a line to only that portion of the data.
model = np.polyfit(x_filt, y_filt, 2)

# And plot things up
fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot(x, y, 'bo')
axes[1].plot(x_filt, y_filt, 'bo')
axes[1].plot(x, np.polyval(model, x), 'r-')

plt.show()

在这里输入图片描述

撰写回答