Search code examples
matlabplot

MATLAB contour plot of 2D scatter


What I want to do is very simple, I just cannot seem to get MATLAB to do it. I would like to plot contours using my 2D data set.

My data set is large; 2 x 844240. I can do a scatter plot just fine,

scatter(Data(1,:), Data(2,:));

Reading through the forums I found Scatter plot with density in Matlab, where a hisogram was plotted. This would suffice, however, I would like to overlay the plots.

enter image description here

The issue is that they have different axis, my scatter data has an axis of [0 0.01 0 2500]; whereas the histogram is [0 100 0 100].

Is there a way to change the axis values of the histogram without modifying the image?

Thanks!


Solution

  • If I understand correctly, you are using hist3 to construct a histogram and then using imagesc to plot it. You can use the second output argument of hist3 to get the histogram bin centers, and then pass those on to imagesc, e.g.

    nBins_x = 100;
    nBins_y = 100;
    [counts, bin_centers] = hist3(Data, [nBins_x nBins_y]);
    x_bin_centers = bin_centers{1};
    y_bin_centers = bin_centers{2};
    imagesc(x_bin_centers, y_bin_centers, counts)
    

    A couple other notes:

    • In your case, you will need to transpose your [2 x N] matrix when passing it to hist3, which expects an [N x 2] matrix.

    • imagesc puts the first axis (which I've been calling the "x" axis) on the vertical axis and the second on the horizontal axis. If you want to flip it, you can use:

      imagesc(y_bin_centers, x_bin_centers, counts')
      
    • If you want to specify the histogram bins explicitly (e.g. to match your scatterplot) you can specify that in the arguments to hist3:

      x_bin_centers = linspace(0, .01, 100);
      y_bin_centers = linspace(0, 2500, 100);
      counts = hist3(Data, {x_bin_centers, y_bin_centers};
      

    And if you want a contour plot, you can use (note that contour takes the axes arguments in a different order than imagesc):

    contour(x_bin_centers, y_bin_centers, counts');
    

    If you are unhappy with the jaggedness of the contours, you may consider using a kernel density estimate instead of a histogram (check out ksdensity) (oops, looks like ksdensity is 1-D only. But there are File Exchange submissions for bivariate kernel density estimation).