Below is a scatter plot I constructed from two numpy arrays.
Scatter Plot Example
What I’d like to add to this plot is a running median of y over a range of x. I’ve photoshoped in an example:
Modified Scatter Plot
Specifically, I need the median for data points in bins of 1 unit along the x axis between two values (this range will vary between many plots, but I can manually adjust it). I appreciate any tips that can point me in the right direction.
4
Answers
I’ve written something like this in
C#
. I don’t do Python so here is the pseudocode:List
to use for the data which the median will be derived fromx
valuex
valueY
value of that point into the median list so that the median list grows as a sorted list. i.e. insert Y so the List value above and below it are > and < it respectively. Take a look here: Inserting values into specific locations in a list in Python .Y
value is added, the median value will be the list value at the current middle index i.e.List(List.Length/2)
Hope it helps!
You can create a function based on
numpy.median()
that will calculate the median value given the intervals:Then use this function for the desired intervals:
I would use
np.digitize
to do the bin sorting for you. This way you can easily apply any function and set the range you are interested in.As an example of the versatility of the method, let’s add errorbars given by the standard deviation of each bin:
This problem can also be efficiently tackled via python pandas (Python Data Analysis Library), which offers native data cutting and analysis methods.
Consider this
(Kudos and +1 to @Hooked for his example from which I borrowed the
X
andY
data)Remark: here the x values of the red curve are the bin-wise x-medians (the midpoints of the bins can be used).