Y-axis lim with Bar/Line overlay

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')

답변 (1개)

Matt Tearle
Matt Tearle 2011년 10월 13일

0 개 추천

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

tmd
tmd 2011년 10월 14일
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!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

질문:

tmd
2011년 10월 13일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by