MATLAB Answers

Use imagesc to plot data extracted from hist3

63 views (last 30 days)
Favier on 23 Mar 2016
Commented: Favier on 24 Mar 2016
Hello, I have two vectors
X = [-1 -5 3 6 -1 7];
Y = [-1 -6 3 6 -1 7];
I want to plot the corresponding number of times each (x,y) couple appears in those vectors on a imagesc plot. For example the couple (-1,-1) appears twice, and all the others only once.
To do so I tried to first use the MATLAB function hist3 to get a 2D histogram of my data:
hist3([X', Y'],[numel(X) numel(Y)]);
This returns the following graph, which looks correct:
But I don't find a 2D histogram very clear and I wanted to use a contour plot to display my data. To use imagesc I did
N = hist3([X', Y'],[numel(X) numel(X)]);
which returns the foolowing graph:
which is absolutely not what I am looking for. The axis are completely out. According to MATLAB documentation, N is "a matrix containing the number of elements of "[X', Y']" that fall in each bin of the grid", it seems to be OK for what I want. Does anybody has an idea on what I am missing here?

Accepted Answer

Charles Dunn
Charles Dunn on 23 Mar 2016
Edited: Charles Dunn on 23 Mar 2016
Be sure to read the documentation of imagesc. The first two inputs, if specified, are used to create the X and Y axes on the plot. However, the function uses ONLY the first and last element of each and linearly interpolates between them. Therefore, you got a linear scale from -1 to 7 for both dimensions. To fix this problem, the axis inputs to imagesc should really be generated directly from the output of hist3, so the bins in your images are identical to the bins from your histogram.
X = [-1 -5 3 6 -1 7];
Y = [-1 -6 3 6 -1 7];
[N,b] = hist3([X', Y'],[numel(X) numel(X)]);
imagesc(b{1}([1 end]),b{2}([1 end]),N);
axis xy equal tight
Note that
axis xy
ensures that the Y axis points up. imagesc expects data in image ij format, which is why the histogram axis was upside down previously.
I also suspect you may want to more carefully define the bins for your histogram as right now the Y bins are slightly larger than your X bins. You should be able to figure this out from the documentation for hist3 if you'd like to change that.
Hope that helps!
  1 Comment
Favier on 24 Mar 2016
Clear and concise answer. Exactly solving my problem. Thank you very much!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!