How to fix the width of bar chart absolutely?
81 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have to plot 2 diffrent bar charts each having different number of data. How can I fix the width of bars absolutely so that the bar appears to be of same breadth in both of the plots?
%% Plot 1
A=10*rand(4,5);
bar(A)
%% Plot 2
A=10*rand(4,4);
bar(A)
0 Commenti
Risposta accettata
Arka
il 8 Mar 2023
Hi,
Since there are different number of bars under each category (5 in the first, 4 in the second), the bars are having different widths.
There are two different solutions that you can adopt. The first is to stack the bars in each category, so the thickness of the bars in both plots will be uniform.
%% Plot 1
A=10*rand(4,5);
bar(A, 'stacked')
figure;
%% Plot 2
B=10*rand(4,4);
bar(B, 'stacked')
The other solution is to calculate the physical space each bar will occupy for a given category, and then use the BarWidth property. Bar width is specified as a fraction of the total space available for each bar. The default value for this is 0.8, i.e. each bar occupies 80% of the width allotted for it, and leaves 10% of the width as space on either side.
In the first matrix, if we consider the total space under each category as 1, we have 1/5 = 0.2 space for each bar, and each bar occupies 80% of the space, i.e. 0.16.
In the second matrix, if we consider the total space under each category as 1, we have 1/4 = 0.25 space for each bar, and each bar occupies 80% of the space, i.e. 0.20.
For the bars in the second plot to occupy 0.16 of space available (which is 0.25), they need to occupy 0.16*100/0.25 = 64% of the space available to them.
Generalizing this calculation, the MATLAB code is:
%% Plot 1
A=10*rand(4,5);
B=10*rand(4,4);
nColA = size(A,2);
nColB = size(B,2);
widthA = (1/nColA);
widthB = (1/nColB);
barWidthA = 0.8*(1/nColA);
barWidthB = 0.8*(1/nColB);
if (barWidthB > barWidthA)
barWidthReq = barWidthA/widthB;
bar(A)
figure;
bar(B, barWidthReq)
else
barWidthReq = barWidthB/widthA;
bar(A, barWidthReq)
figure;
bar(B)
end
If you wish to learn more about the bar function and its properties, please check out the MathWorks documentation link below:
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Annotations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!