Why is creating a handle for a bar graph delecting half of my plot?
Show older comments
I am trying to create a plot of number of rainy days each month for each of three cities. The first part of my code for this is:
% code
>>f1=figure
>>xlab=['Jan';'Feb';'Mar';'Apr';'May';'Jun';'Jul';'Aug';'Sep';...
'Oct';'Nov';'Dec'];
>> bar(Month,[RainDaysP, RainDaysSS, RainDaysM])
>> set(gca,'XTickLabel',xlab)
>> axis([0 13 0 31])
>> ylabel('Number of rainy days','fontsize',16)
>> xlabel('Month','fontsize',16)
>> set(gca,'fontsize',16,'ticklength',[0.02,01])
Then I wanted to change the colour of each bar seperately, so I created a bar handle. My whole code is now:
% code
>>f1=figure
>>xlab=['Jan';'Feb';'Mar';'Apr';'May';'Jun';'Jul';'Aug';'Sep';...
'Oct';'Nov';'Dec'];
>> bar(Month,[RainDaysP, RainDaysSS, RainDaysM])
>> set(gca,'XTickLabel',xlab)
>> axis([0 13 0 31])
>> ylabel('Number of rainy days','fontsize',16)
>> xlabel('Month','fontsize',16)
>> set(gca,'fontsize',16,'ticklength',[0.02,01])
>> p=bar(Month,[RainDaysP,RainDaysSS,RainDaysM])
>> set(p(1),'facecolor',[0 1 1])
>> set(p(2),'facecolor',[1 0 1])
>> set(p(3),'facecolor',[1 1 0])
My difficulty is that the first set of code produced a correct plot, however whenever I introduce the 'p=bar...' line I have been getting many problems. First the colours changed correctly, however the range of my y axis was now only up to 25 and not 31 as specified, and also I no longer had my x axis tick labels (showing the months), just numbers 1 to 12. Now, when I introduce the 'p=bar...' line, the only change that happens is that I lose half of my bar graph. The months now only show January through to July.
Any advice on where I am going wrong would be much appreciated. I have tried varying the code with 'hold on'/'hold off' to see if it makes a difference, but nothing has gotten me the graph I am looking for.
Answers (1)
Walter Roberson
on 13 Nov 2016
hold on
That is, the problem is that bar() is a high-level graphics operator that by default will erase whatever content you have in your current axis, as is the case for all high-level graphics operations. If you want to preserve the current content you need to use the hold call.
1 Comment
Joanna Lada
on 13 Nov 2016
Categories
Find more on Bar Plots 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!