MATLAB: Bar Plot with 2 Y axes and same X- axis

barchartplottingplotyy

Hi , I have 2 vectors called R_per and A_per with some distinct values. They share a common base called the per.
I need to plot both R_per and A_per w.r.t Per in a Bar plot. The bar must be grouped as shown in this picture:
I tried using plotyy and did the wrote the following code:
[hyy,hl,ho]=plotyy(per , A_per, per, R_per,'bar','bar');
xt = get(gca, 'XTick');
set(gca, 'XTick', xt, 'XTickLabel', {'200' '300' '400' '500' '700'})
set(ho,'facecolor','r','barwidth',0.2)
set(hl,'facecolor','g','barwidth',0.3)
What i get is a overlapped bar plot with uneven spacing and unclean Y axes.
Can someone help ?
Thanks in advance.
Regards, Vittal

Best Answer

Since the two calls to bar in plotyy are independent of each other, there's no way for the information that you want two independent bar plots to look like together they're grouped. Fortunately, there's a relatively simple way to fake it -- will just use a trivial example rather than try to explain; the "trick" should be self-evident.
N=5; % number of bars
y1=rand(N,2); y2=100*rand(N,2); % dummy disparate-magnitude data sets
y1(:,2)=nan;y2(:,1)=nan; % NB: column 2, then column 1 are set NaN
x=[1:N].'; % use the serial index to plot against
hAx=plotyy(x,y1,x,y2,@bar,@bar); % plot, save axes handles
set(hAx(2),'xtick',[]) % turn off labels on RH x-axis; keep only one set
set(hAx(1),'xticklabel',[200:100:500 700]) % tick labels on first...
Well, I'll try to add some explanatory words too, despite the promise... :)
The "trick" is to make the data arrays the number of columns wide that you need grouped bars (here, two, one for each y-axis); it's over columns that Matlab 'group' works. All the HG plot routines have the feature that NaN is handled gracefully simply by not being plotted but the place holder is still there. Hence, as above, there are two bars for each plot but by swapping which column is NaN, one is drawn left, the other right of center and voila! you've got the appearance of 'group' with disparate bar graphs...
Salt to suit with your own data, of course.