如果 x 条目满足条件 python,则绘制 xy 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14788459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plot x-y data if x entry meets condition python
提问by 8765674
I would like to perform plots/fits for x-y data, provided that the data set's x values meet a condition (i.e. are greater than 10).
我想对 xy 数据执行绘图/拟合,前提是数据集的 x 值满足条件(即大于 10)。
My attempt:
我的尝试:
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
Perhaps it would be better to remove x-y entries for rows where the x value condition is not met, and then plot/fit?
也许最好删除不满足 x 值条件的行的 xy 条目,然后绘制/拟合?
采纳答案by Joe Kington
Sure, just use boolean indexing. You can do things like y = y[x > 10].
当然,只需使用布尔索引。你可以做类似的事情y = y[x > 10]。
E.g.
例如
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()



