problem with adding second x-axis linked to first x-axis
3 ビュー (過去 30 日間)
古いコメントを表示
My goal is to have a graph with 2Y-axis plotting data linked by the bottom x-axis. I want to add a top x-axis which is linked to the bottom x-axis by an equation too. So I get 4 graphs in one at the end. This figure at the end is part of a larger 2x2 subplots configuration (not done below)
ISSUES: the top x-axis does not have the correct lenght/scale (smaller or larger than the figure); and it is not moving correctly with the figure is magnified or reduced, so we got a wrong scaling.
How can I correct this issue ?
Thanks in advance for any help :)
Example of program below:
X1=1:1:1000;
Y1=X1.^2;
Y2=1./X1;
%variables to plot
yyaxis left
%for the data to be plotted with left y-axis
H1=loglog(X1,Y1);
h=title('Title');
P = get(h,'Position');
set(h,'Position',[P(1)-90 P(2)+40 P(3)]) ;
%to move a bit the title position
%hold on
ylabel('Y axis','fontsize',20);
xlabel('X axis','fontsize',20);
grid on
yyaxis right
%for the data to be plotted with right y-axis
H2=semilogx(X1,Y2,'k');
ylabel('Y axis 2','fontsize',20);
%hold off
box off
%to hide the outside box before inserting new top x-axis
ax1=gca;
ax2 = axes('position', get(ax1, 'position'));
%to add a new x-axis on top of previous one
set(ax2, 'XAxisLocation', 'Top', 'color', 'none', 'Xdir','reverse');
ax2.YAxis.Visible = 'off';
%to position the axis on top and display correctly the values
X_lim=get(ax1,'XLim');
ax2.XLim=[ -10*log10(X_lim(2))+39 -10*log10(X_lim(1))+39];
xticks(-10*log10(X_lim(2))+39:2:-10*log10(X_lim(1))+39);
%to link the value of top x-axis with values of bottom x-axis
xlabel('X axis 2');
legend([H1 H2],'Legend 1','Legend 2');
%display legend and title
0 件のコメント
回答 (1 件)
OCDER
2017 年 9 月 22 日
編集済み: OCDER
2017 年 9 月 22 日
To resolve the top axis label going off the figure, reset ax1 and ax2 positions based on the minimum border required (TightInset). Add this to the end of your script:
TightInset = max([ax1.TightInset; ax2.TightInset]); %[Left, Bot, Right, Top] border needed
AxPos = [TightInset(1), TightInset(2), 1-sum(TightInset([1 3])), 1-sum(TightInset([2 4]))]; %New position
ax1.Position = AxPos;
ax2.Position = AxPos;
3 件のコメント
OCDER
2017 年 9 月 25 日
Hi David, yes, this is generally the right approach to resizing subplots to fill the white space. To be precise though, you have to do some calculations with axes positions and tight insets. There might be a function that does all this calculation for you in the Matlab Exchange, but check out this Q&A too:
参考
カテゴリ
Help Center および File Exchange で Axes Appearance についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!