How to fix the width of bar chart absolutely?
57 次查看(过去 30 天)
显示 更早的评论
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)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1317665/image.jpeg)
%% Plot 2
A=10*rand(4,4);
bar(A)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1317670/image.jpeg)
0 个评论
采纳的回答
Arka
2023-3-8
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Bar Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!