Making a histogram with two variables in the same graph
57 views (last 30 days)
Show older comments
I have two variables, z1 and z2, which are two vectors with 1000 enteries. They represent distances calculated by two algoritmes for the traveling salesman problem.
Both vectors have values ranging from roughly 12 000 to 19 000 (km). I want a histogram showing both variables, with bins starting from 12 000 ending at 19 000 with a range of 100 per bin. the variables should both be a different color (lets say z1 red and z2 blue).
How could I do this?
0 Comments
Accepted Answer
More Answers (2)
Jan
on 17 May 2022
Another way of solving this is to create the histogram counts separately and plot the results with a bar() graph.
binEdges = [12000:100:19000];
histogr = [histcounts(z1, binEdges); ...
histcounts(z2, binEdges)];
bar(binEdges(1:end-1).', histogr.')
This way you have several ways of presenting the data, that the histogram function doesn't provide.
0 Comments
Image Analyst
on 13 Dec 2019
You can try this:
% Create sample data.
z1 = 7000 * randn(1, 1000) + 12000;
z2 = 7000 * randn(1, 1000) + 12000;
% Create histogram
subplot(2, 1, 1);
binEdges = 12000:100:19000;
histObject = histogram2(z1, z2, binEdges, binEdges);
xlabel('z1 value', 'fontSize', fontSize);
ylabel('z2 value', 'fontSize', fontSize);
zlabel('Count', 'fontSize', fontSize);
title('100 pairs of distances', 'fontSize', fontSize);
subplot(2, 1, 2);
counts = histObject.Values;
imshow(counts);
colorbar
colormap(hsv(256));
title('Counts as an image', 'fontSize', fontSize);
![0000 Screenshot.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/254372/0000%20Screenshot.png)
but actually, since most bins have only 1 count in them, you may just want to use scatter() instead of histogram to see if there's a pattern.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!