Matlab scatter plot with lowess curve

935 Views Asked by At

I'm writing a research paper and want to plot something like this from my dataset

enter image description here

Basically it's a Matlab scatter plot with a lowess curve showing the average value at each bin

I've been searching Google for 2 days and couldn't find a solution or a piece of sample code to do that yet

Stack Overflow is now my last resort :)

2

There are 2 best solutions below

2
dustincarr On BEST ANSWER

This is the simplest code I can come up with. This assumes you have your data in x and y vectors.

%adjust bins accordingly, or add a line that calculates them based on range.
bins = -0.5:0.01:0.5;
nBins = length(bins);

for index = 1:(nBins-1)

  binVec = (x >= bins(index) & x < bins(index+1));
  lowess(index) = mean(y(binvec));

end
%note that bins are shifted by one half step.
plot(x,y,'.',bins+0.005,lowess,'--r');

It is possible to vectorize this, but it is not worth it. At least the way I found would make it unreadable and marginally more efficient, if at all.

1
John On

A rough answer, is, use http://www.mathworks.com/matlabcentral/fileexchange/13352 to do the density scatter plot, and use histc in matlab to generate the lowess curve at an appropriate resolution, and use hold plot on your density plot to draw