gpt4 book ai didi

python - 如果 x 条目满足条件 python,则绘制 x-y 数据

转载 作者:太空狗 更新时间:2023-10-30 00:25:21 26 4
gpt4 key购买 nike

我想对 x-y 数据进行绘图/拟合,前提是数据集的 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 值条件的行的 x-y 条目,然后绘图/拟合?

最佳答案

当然,只需使用 bool 索引。您可以执行类似 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()

enter image description here

关于python - 如果 x 条目满足条件 python,则绘制 x-y 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14788459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com