Issue
# imports
import numpy as np
import matplotlib.pyplot as plt
Problem
I have a 2 arrays, representing datapoints on a line. For example:
x = np.array([0,1,2])
y = np.array([5,6,4])
Plot the data:
plt.plot(x,y)
plt.scatter(x,y,c='r')
Get:
I'd like to have arrays where the datapoints represent the same lines as above, but they are doubled. The desired result is:
new_x = np.array([0,0.5,1,1.5,2]) # this is the result I am looking for
new_y = np.array([5,5.5,6,5,4]) # this is the result I am looking for
Plot:
plt.plot(new_x,new_y)
plt.scatter(new_x,new_y,c='r')
Result:
My attempt
My method of doing this:
x = np.array([0,1,2])
y = np.array([5,6,4])
new_x=[]
for index, each in enumerate(x):
if index!=0:
new_x.append((each+x[index-1])/2)
new_y=[]
for index, each in enumerate(y):
if index!=0:
new_y.append((each+y[index-1])/2)
new_x.extend(x)
new_y.extend(y)
Plot:
plt.plot(new_x,new_y)
plt.scatter(new_x,new_y,c='r')
Result:
Points are in the right place, the new points added are the correct points, but they are put into the new_x
& new_y
arrays in the wrong order. It is fixable by paying more attention to the .extend
, but this does not seem a good method to me anyway, because of the iteration.
My research
- linear interpolation between two data points: doesn't use 2D arrays
- How to write a function that returns an interpolated value (pandas dataframe)?: deals with interpolated values of functions, not resampling lines as above
And there are some other questions with the [interpolation]
tag, but I haven't found one descibing this problem above.
Question
How do I get the above described new_x
and new_y
, preferably without iteration?
Solution
You could use these one-liner list comprehensions:
new_x = [j for i, v in enumerate(x) for j in [v, (x[i] + x[(i + 1 if (len(x) - 1) != i else i)]) / 2]]
new_y = [j for i, v in enumerate(y) for j in [v, (y[i] + y[(i + 1 if (len(y) - 1) != i else i)]) / 2]]
plt.plot(new_x, new_y)
plt.scatter(new_x, new_y, c='r')
plt.show()
Output:
Answered By - U12-Forward
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.