Use imagesc to plot data extracted from hist3

조회 수: 8 (최근 30일)
Favier
Favier 2016년 3월 23일
댓글: Favier 2016년 3월 24일
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)]);
figure
imagesc(X,Y,N);
colorbar
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?

채택된 답변

Charles Dunn
Charles Dunn 2016년 3월 23일
편집: Charles Dunn 2016년 3월 23일
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)]);
figure
imagesc(b{1}([1 end]),b{2}([1 end]),N);
colorbar
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
Favier
Favier 2016년 3월 24일
Clear and concise answer. Exactly solving my problem. Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by