Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot x-y data if x entry meets condition python

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).

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?

like image 298
8765674 Avatar asked Feb 09 '13 13:02

8765674


People also ask

How do you set X and Y axis ranges in python?

To set range of x-axis and y-axis, use xlim() and ylim() function respectively. To add a title to the plot, use the title() function. To add label at axes, use xlabel() and ylabel() functions. To visualize the plot, use the show() function.


1 Answers

Sure, just use boolean indexing. You can do things like 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()

enter image description here

like image 146
Joe Kington Avatar answered Oct 04 '22 03:10

Joe Kington