XTick labels and Stacking in bar plot

84 views (last 30 days)
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')

Accepted Answer

Thorsten
Thorsten on 29 Sep 2015
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

More Answers (1)

Mike Garrity
Mike Garrity on 29 Sep 2015
Edited: Mike Garrity on 29 Sep 2015
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'});
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:
Of course, you can trim that off by using the xlim function:
xlim([.5 1.5])

Categories

Find more on Color and Styling 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!