Extract data using histogram2()
12 views (last 30 days)
Show older comments
Is it possible to extract data (x-coordinates and y-coordinates) using the syntax histogram2()?
Accepted Answer
sagun subedi
on 1 Jul 2020
1 Comment
Steven Lord
on 1 Jul 2020
isInFirstBin = (binx == 1 & biny == 1);
pointsInFirstBin = location(isInFirstBin, :)
isInBin12 = (binx == 1 & biny == 2);
pointsInBin12 = location(isInBin12, :)
More Answers (2)
Steven Lord
on 1 Jul 2020
If you want the data that was passed into histogram2 retrieve the Data property of the histogram.
If you want the edges of the bins, get the XBinEdges and YBinEdges properties.
For the bin counts (raw or with the specified Normalization applied) see the BinCounts and Values properties.
If none of those are what you mean by "data" please clarify what specifically you want to extract.
4 Comments
Steven Lord
on 1 Jul 2020
Please show a small sample of your data, show how you called histcounts2 on that data, and explain what "not working" means. Did it not give you the results you expected? Did it throw an error and if it did what was the full text of that error, all the text in red? With this information we may be able to help you do what you asked.
Image Analyst
on 1 Jul 2020
Try this:
clc; % Clear the command window.
fprintf('Beginning to run %s.m.\n', mfilename);
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
numPoints = 20;
xy = rand(numPoints, 2); % Representing x and y coordinates
plot(xy(:, 1), xy(:, 2), 'b.', 'MarkerSize', 20);
grid on;
xEdges = [0, 0.5, 1];
yEdges = [0, 0.25, 0.5, 0.75, 1];
xticks(xEdges);
yticks(yEdges);
xlim([min(xEdges), max(xEdges)]);
ylim([min(yEdges), max(yEdges)]);
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
counts = histcounts2(xy(:, 1), xy(:, 2), xEdges, yEdges)
% With counts, the x counts are rows and the y are columns.
% Place the count in each bin
for kx = 1 : size(counts, 1)
xt = mean([xEdges(kx), xEdges(kx + 1)]);
for ky = 1 : size(counts, 2)
yt = mean([yEdges(ky ), yEdges(ky + 1)]);
textLabel = sprintf('Count = %d', counts(kx, ky));
text(xt, yt, textLabel, 'Color', 'r', 'FontSize', 12, 'HorizontalAlignment', 'center');
end
end
fprintf('Done running %s.m.\n', mfilename);
0 Comments
See Also
Categories
Find more on Histograms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!