How to plot Histogram/bar graph for two data sets!!
74 views (last 30 days)
Show older comments
I have data set having two variables say EQ and MASS. Their length is same. I can plot the scatter plot as shown.
What i want to do is to plot a histogram between the EQ and MASS showing that how much MASS is present at which EQ. I mean summing the scatter points at each EQ and showing it as a bar graph or histogram.
Can anyone guide me..I have tried but as i see histogram can be plotted for only one variable and no of bins.
Also I have tried combining them as one variable and plotting but still now working....
0 Comments
Accepted Answer
Dave B
on 27 Nov 2021
I think there are a few ways to interpret your question.
Do you mean you want to show two bar charts describing the histogram of the two variables? This will be awkard to do on one x-axis because the scales are very different:
load sat
figure
histogram(EQ)
hold on
histogram(MASS)
figure
tiledlayout(2,1)
nexttile;histogram(EQ)
nexttile;histogram(MASS)
But I think what actually wanted is a 2-D (bivariate) histogram, showing a 3-D bar? histogram2 is good for this...
figure
histogram2(EQ,MASS)
xlabel('EQ')
ylabel('MASS')
zlabel('Count')
If I did this, I might consider trying to flip the x and y axis directions so that the tall bars are in the back corner (because it's hard to see what they might obscure):
figure
histogram2(EQ,MASS)
set(gca,'XDir','reverse','YDir','reverse')
xlabel('EQ')
ylabel('MASS')
zlabel('Count')
Although I generally think these are better with a image-like display style:
histogram2(EQ,MASS,'DisplayStyle','tile')
xlabel('EQ')
ylabel('MASS')
c=colorbar;
c.Label.String='Count';
Or maybe you just wanted to capture histograms alongside the scatter above? You can do this manually using histogram, scatter, and tiledlayout...normally I'd recommend the function scatterhistogram for this but it sadly doesn't look right here.
figure
t=tiledlayout(1,1,'TileSpacing','tight');
scatax=nexttile;
scatter(EQ,MASS)
ax=axes(t);
ax.Layout.Tile='north';
histogram(ax,EQ)
ax.XLim = scatax.XLim;
ax.Visible='off';
ax=axes(t);
ax.Layout.Tile='east';
histogram(ax,MASS)
view([90 90])
ax.XDir='reverse';
ax.XLim = scatax.YLim;
ax.Visible='off';
5 Comments
Dave B
on 27 Nov 2021
It's pretty easy to plot two datasets with bar, but to combine this with groupsummary it will be important to give it the same exact bins. So instead of specifying the number of bins, you'll want to provide groupsummary with some specific bins:
load sat
MASS2=MASS+(rand(size(MASS))-.5)*1e-9;
EQ2=EQ+rand(size(EQ))-.5;
[msum,~]=groupsummary(MASS,EQ,10,@sum);
[msum2,bx]=groupsummary(MASS2,EQ2,10,@sum);
bar(bx,[msum msum2])
xlabel('EQ Range')
ylabel('Sum(MASS)')
legend(["MASS1","MASS2"])
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots 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!