Making a histogram with two variables in the same graph

48 vues (au cours des 30 derniers jours)
Kerr Beeldens
Kerr Beeldens le 13 Déc 2019
Modifié(e) : Adam Danz le 17 Mai 2022
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?

Réponse acceptée

Adam Danz
Adam Danz le 13 Déc 2019
Modifié(e) : Adam Danz le 17 Mai 2022
% create z1 and z2 values
z1 = rand(1,1000)*7000 + 12000;
z2 = rand(1,1000)*7000 + 12000;
% bin and plot
binEdges = 12000:100:19000;
h1 = histogram(z1,binEdges);
hold on
h2 = histogram(z2,binEdges);

Plus de réponses (2)

Jan
Jan le 17 Mai 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.

Image Analyst
Image Analyst le 13 Déc 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
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.

Community Treasure Hunt

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

Start Hunting!

Translated by