Plot figure with two x axes and resize without destroying bounding box

17 views (last 30 days)
I'm trying to plot a figure with two x axes (just one dataset is plotted, with different x axis values on the top AND bottom). I'm not able to 'link' the axes in a way that ensures the bounding lines don't get completely messed up when I resize the figure.
I've also tried using plotxx but the axis labels get cut off when resizing.
Here is the code I am using:
hAx(1)=gca;
plot(hAx(1),abs(E_avg_z)/1e6,g_f,'LineWidth',2)
set(hAx(1),'box','off')
hAx(1).XLim=[abs(E_avg_z(1))/1e6 abs(E_avg_z(end))/1e6];
hAx(2)=axes('XAxisLocation','top','YAxisLocation','right','color','none');
hAx(2).XLim=[0.01 0.4];
hAx(2).YTick=[];
set(hAx,'fontweight','bold'); % default fontsize is 10
set(hAx,'fontsize',16); % default fontsize is 10
set(gcf,'color','w');
Now if I try to resize the figure:
set(gcf, 'Units', 'centimeters', 'Position', [0, 0, 10, 50], 'PaperUnits', 'Inches', 'PaperSize', [20,20])
Then I get this:
I don't know how to fix this axis scaling error.

Answers (1)

Devyani Maladkar
Devyani Maladkar on 23 Aug 2021
Hello ,
It is my understanding that you want to plot a single dataset with two x axes (above and below) and one y-axis. It appears you are facing a difficulty in resizing of the plot using set which causes the x-axis to overlap.
To plot data with two x-axes and prevent the axis overlap issue one can use the tiled chart layout and create a 1x1 tiled layout object. The 2nd x-axis can be specified using the axes function called on the object . I have attached the code below, to plot the data using two x-axes and ensure no overlap or no labels are cut off. To replicate your issue, I have used sample data as below. More information in detail can be found here.
%Sample data to plot
x1 = 0:0.1:40; % x-axis coordinate for data
y1 = 4.*cos(x1)./(x1+2)+1200; % y-axis coordinate for data
% Setting up the first x axis and y-axis
t = tiledlayout(1,1);
ax1 = axes(t);
plot(ax1,x1,y1);
ax1.XLim=[x1(1) x1(end)];
xlabel(ax1,'Electric Field (Mv/m) ');
ylabel(ax1,'g-factor');
ax1.Box = 'off';
% Setting up the second x axis
ax2 = axes(t,'YTick',[],'XAxisLocation','top','YAxisLocation','right','color','none');
ax2.XLim=[1 20];
ax2.FontSize=16;
xlabel(ax2,'Plunger Voltage (V)');
ax2.Box = 'off';
set(gcf,'color','w');
set(gcf, 'Units', 'normalized', 'Position', [0, 0, 10, 50], 'PaperUnits', 'Inches', 'PaperSize', [20,20])
To prevent the label cutoff issue you can use normalized setting for units, this documentation has more details on Units and Position when using normalized.
Best Regards,
Devyani

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!