
How can I change the location of bar edges, and the number of bars for histogram made with histfit?
    11 views (last 30 days)
  
       Show older comments
    
I am trying to plot two histogram with distributions on the same figure, both made with histfit. The two histograms have different data sets, but i would like the width, start and end of the bars to be the same for both histograms. Is this possible?
0 Comments
Answers (1)
  Kanishk
 on 3 Jul 2025
        Hello Hugo,
I understand you want to plot two histograms with fitted distributions on the same figure, using histfit, and ensure both histograms share the same bin width, start, and end points. Since the "histfit" function does not allow you to directly specify bin edges, a workaround is to manually control the histogram bins and fit the distributions separately.
% Example data
data1 = randn(1000,1) * 2 + 5;
data2 = randn(1000,1) * 1 + 7;
binedges = linspace(min([data1; data2]), max([data1; data2]), 20);
binwidth = binedges(2) - binedges(1);
centers = binedges(1:end-1) + binwidth/2;
[counts1, ~] = histcounts(data1, binedges);
bar(centers, counts1, 'FaceAlpha', 0.5, 'FaceColor', 'b');
hold on;
pd1 = fitdist(data1, 'Normal');
x_values = linspace(min(binedges), max(binedges), 100);
y1 = pdf(pd1, x_values) * numel(data1) * binwidth;
plot(x_values, y1, 'b-', 'LineWidth', 2);
[counts2, ~] = histcounts(data2, binedges);
bar(centers, counts2, 'FaceAlpha', 0.5, 'FaceColor', 'r');
pd2 = fitdist(data2, 'Normal');
y2 = pdf(pd2, x_values) * numel(data2) * binwidth;
plot(x_values, y2, 'r-', 'LineWidth', 2);
xlabel('Value');
ylabel('Count');
legend('Class A Histogram', 'Class A Fit', 'Class B Histogram', 'Class B Fit');
title('Overlaid Histograms with Fitted Distributions');
grid on;

This method allows you to fully control the histogram binning and ensures consistency across both datasets. Additionally, fitting the distributions manually using fitdist and pdf gives flexibility in presentation and scaling.
Hope this helps!!
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!
