Bar plot with two Y-axes

35 views (last 30 days)
pietro
pietro on 29 Nov 2014
Commented: dpb on 14 Nov 2016
Hi all,
I need to plot data in a bar plot with two Y axis. Morevover the bar must be grouped, like in the following picture:
I have tried the following code but the result is far to be fine.
figure
a=rand(10,1)*100;
b=rand(10,1)*5;
[AX,H1,H2] =plotyy([1:10],a, [1:10]-0.5,b, 'bar', 'bar');
set(H1,'FaceColor','r')
the problems are:
  • Item one: There are two overlapped x-axis, but I need only one.
  • Item two: the bars are not each next to the other,
Thank you
best regards
  1 Comment
dpb
dpb on 29 Nov 2014
I don't have time to play at the moment but I see two possible modes of attack
1) And probably(?) simplest -- put the data all in one array; scale them to fit on the one axes based on the desired scale for the two. Then put the second axes on manually with its scale for display only.
2) Make the x-axes commensurate; put the same number of bars in each but use NaN for the missing data in the LH/RH bars for the respective RH/LH axes.

Sign in to comment.

Accepted Answer

Orion
Orion on 29 Nov 2014
Hi,
try this
figure
a=[rand(10,1)*100 zeros(10,1) ];
b=[zeros(10,1) rand(10,1)*5 ];
[AX,H1,H2] =plotyy([1:10],a, [1:10],b, 'bar', 'bar');
set(H1,'FaceColor','r') % a
set(H2,'FaceColor','b') % b
  3 Comments
dpb
dpb on 29 Nov 2014
2) above w/ zeros rather than NaN...
pietro
pietro on 30 Nov 2014
Using Orion's method I cannot set the legend. Here an example:
figure
a=[rand(10,1)*100 zeros(10,1) ];
b=[zeros(10,1) rand(10,1)*5 ];
[AX,H1,H2] =plotyy([1:10],a, [1:10],b, 'bar', 'bar');
set(H1,'FaceColor','r') % a
set(H2,'FaceColor','b') % b
legend('Absolute','Percentage')
Running this code I get only two red entries in the legend. How may I solve it?

Sign in to comment.

More Answers (1)

dpb
dpb on 30 Nov 2014
Edited: dpb on 30 Nov 2014
...I get only two red entries in the legend. How may I solve it?
Use the handles, Luke... :) You've faked which bars are to be seen but have duplicates so have to use the handles associated with the two bars only of the ones that are wanted to be observed. Hn are each 2-vectors; use the first of each --
hLgnd=legend([H1(1) H2(1)],'Absolute','Percentage');
  6 Comments
Dirk
Dirk on 14 Nov 2016
How could you place error bars onto the plot above?
dpb
dpb on 14 Nov 2016
Depends on which release...HG2 broke the HG1 solution...here's a link to the issues... <barweb-in-2014b-doesn-t-work-any-more>
The links in the RH side in this case are useful as well...

Sign in to comment.

Categories

Find more on Two y-axis 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!