XTick labels and Stacking in bar plot
189 次查看(过去 30 天)
显示 更早的评论
I have two questions: 1. I am not getting the XTick labels for the green colored bar using code1. I don't know how to stop this overlapping of xtick labels.
% code1
PErr = [235.6923 5.5125];
wd = 0.2;
bar(1,PErr(1),wd,'facecolor','r');
set(gca,'XTickLabel',{'MODEL1'});
hold on;
bar(2,PErr(2),wd,'facecolor','g');
set(gca,'XTickLabel',{'MODEL2'});
2. I want to stack the bars graph for these two values, but i am not getting stacked bars. The larger bar need to be in red and smaller in blue. Thank you.
PErr = [235.6923 5.5125];
wd = 0.2;
bar(PErr,'stacked')
0 个评论
采纳的回答
Thorsten
2015-9-29
1.
bar(1, PErr(1),'FaceColor', 'r')
hold on
bar(2, PErr(2),'FaceColor', 'b')
set(gca, 'XTick', [1 2])
set(gca, 'XTickLabel', {'Model1' 'Model2'})
2. Stacked works only if you have more than one bar. So you have to add another fake bar using nan and adjust the x-axis
bar([PErr; nan(1,2)], 'stacked')
a = axis; axis([a(1) a(2)-0.8 a(3:4)]); % -0.8 selected such that it looks nice
0 个评论
更多回答(1 个)
Mike Garrity
2015-9-29
编辑:Mike Garrity
2015-9-29
In the first (grouped) case, you're probably going to be more successful if you have the two series share a common XData. That'd look something like this:
x = [1 2];
PErr = [235.6923 5.5125];
wd = 0.2;
bar(x,[PErr(1) nan],wd,'facecolor','r');
hold on
bar(x,[nan PErr(2)],wd,'facecolor','g');
set(gca,'XTickLabel',{'MODEL1','MODEL2'});
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/178538/image.png)
In the stacked case, you're probably going to run into some pain because you'll only have a single bar. The bar function has some funny old quirks about what it should do when the XData is scalar. As you can see from this example,
for nbars=5:-1:1
x = 1:nbars;
y = rand(nbars,2);
bar(x,y,'stacked')
pause(1)
end
the "right" thing should probably be this:
bar(1,PErr','stacked')
But it errors out saying:
X must be same length as Y.
You can work around this by adding a dummy column:
x = [1 2];
y = [PErr; nan, nan];
h = bar(x,y,'stacked');
h(1).FaceColor = 'red';
h(2).FaceColor = 'blue';
But that's going to get added into your XLim:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/178539/image.png)
Of course, you can trim that off by using the xlim function:
xlim([.5 1.5])
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/178540/image.png)
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!