Making a contour plot from x and y data

11 views (last 30 days)
Markus Similä on 21 Jul 2020
Commented: Markus Similä on 23 Jul 2020
I have a two column vector containing x and y values. The y values have a high accuracy (many decimal points).
x ranges from 0 to 50000 and y from 0 to 14.
I need to use contourf to make a 2d representation of this data.
How can this be done?

Markus Similä on 22 Jul 2020
I need to show the density of the data points. Sorry, should have been more specific.
KSSV on 22 Jul 2020
Markus Similä on 22 Jul 2020
The data looks something like this. There are a lot more data points (millions).
Oops, I missed a zero on the range of the x.
35847 1.547
6062 2.172
115733 2.282
33021 1.760
35769 1.772
35872 2.030
55739 2.298
55266 0.693
55348 0.693
1409 1.605
1685 2.059
33735 1.615
50968 2.043
60111 1.637
74971 2.217
55397 1.431
1810 1.321
54242 2.581
35771 0.944
2118 1.782
34322 2.127
1943 1.743
1758 1.721
168417 0.583
129397 1.737
76477 1.624
91810 1.150
76881 1.669
223104 1.834
4048 2.066
5170 1.524

Adam Danz on 22 Jul 2020
Edited: Adam Danz on 22 Jul 2020
The bivariate density can be computed using histcounts2. You'll need to specify either the number of bins or the bin edges for the x and y variables using one of the syntaxes below.
Here's what the solution will look like. xy is your nx2 matrix of [x,y] values.
[N,Xedges,Yedges] = histcounts2(xy(:,1), xy(:,2), 5);
% or use [N,Xedges,Yedges] = histcounts2(X,Y,Xedges,Yedges);
% Compute bin centers
Xcnt = Xedges(2:end) - abs(diff(Xedges(1:2))/2);
Ycnt = Yedges(2:end) - abs(diff(Yedges(1:2))/2);
figure()
contour(Xcnt,Ycnt, N)
% show bins
xlim = [min(Xedges),max(Xedges)];
ylim = [min(Yedges),max(Yedges)];
arrayfun(@(x)xline(x,'Color',[.8 .8 .8]),Xedges)
arrayfun(@(y)yline(y,'Color',[.8 .8 .8]),Yedges)
% colorbar
cb = colorbar();
ylabel(cb,'density')

1 Comment

Markus Similä on 23 Jul 2020
Thank you!
This is what I was trying to do as well.

KSSV on 22 Jul 2020
1. You need to generate z values which are density values.
2. I would fix a distance r and calculate the number of points within r for each point using rangesearch.
3. Now you can use scatter to plot the density values.
4. If your data is structured arrange the data and use contourf.