Y-axis lim with Bar/Line overlay

9 views (last 30 days)
tmd
tmd on 13 Oct 2011
Hello,
I've made a 2 series bar graph with a line graph overlay. For the purposes of the data, both Y-axis need to be the same. I am able to set the line graph axis to the bar graph YLim but not the other way around.
Sometimes the line graph has larger Y values than the bar graph and it therefore gets cutoff. I would like to be able to detect which YLim should be used and make them both the same. How can this be done?
Current code is below.
Thank you!
figure;
h_bar = bar(_data(:,1),Y);
set(gca, 'XTick',_data(:,1));
set(gca, 'XTickLabel', _data(:,1));
h1 = gca;
h2 = axes('Position',get(h1,'Position'));
plot(_data(:,1),Y2,'LineWidth',2,'Color','red')
set(h2,'YAxisLocation','right','Color','none','XTickLabel',[])
set(h2,'XLim',get(h1,'XLim'),'Layer','top')
set(h2,'YLim',get(h1,'YLim'),'Layer','top')

Answers (1)

Matt Tearle
Matt Tearle on 13 Oct 2011
figure;
h_bar = bar(_data(:,1),Y);
set(gca, 'XTick',_data(:,1));
set(gca, 'XTickLabel', _data(:,1));
h1 = gca;
h2 = axes('Position',get(h1,'Position'));
plot(data,Y2,'LineWidth',2,'Color','red')
set(h2,'YAxisLocation','right','Color','none','XTickLabel',[])
set(h2,'XLim',get(h1,'XLim'),'Layer','top')
% Query both axes' y-limits
yl = [get(h1,'YLim');get(h2,'YLim')];
% Find the lower and upper limits of both
yl = [min(yl(:,1)),max(yl(:,2))];
% Set y-limits for both axes
set(h1,'YLim',yl)
set(h2,'YLim',yl)
  1 Comment
tmd
tmd on 14 Oct 2011
Matt, Thanks for the response. The code you provided does not work as intended. The reason I believe is because the line plot axis (h2) is originally being set to be equal to h1. However, your response did inspire a less elegant solution that seems to be working.
if max(_data(:,1) > Y
Y_Lim = max(_data(:,1)) + 2;
set(gca,'YLim',[0 Y_Lim]);
end
Thanks again!

Sign in to comment.

Categories

Find more on Graph and Network Algorithms 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!