Vertical subplot dimensions do not match
Mostrar comentarios más antiguos
Hi! I'm trying to create a figure with two subplots disposed vertically, which have the same dimension along the xaxis. To do that, I saved the subplot axes as variables "ax1" and "ax2", then I added the following line in my program, at the end of the generation of the subplots:
ax2.Position(3) = ax1.Position(3);
Weird thing happens: when I launch the previous command after the code has finished running, it works properly and it changes the second plot x dimension in order to be equal to the first one, as required. BUT if I simply add the line at the end of the code and I run the code all toghether, it completely messes up the x dimension of the second plot. Furthermore, if I add a pause before the command, it works properly.
It seems that in order to work correctly, the command needs to be applied after the figure has been created, but I don't understand why. Is there a bug in Matlab subplot creation? My Matlab version is R2023b Update 3 (23.2.0.2409890).
Here is an example (pause at the penultimate line is commented, to replicate the issue):
close all; clear; clc;
x = 0:0.1:100;
xmin = 0; xmax = 100; xstep = 5;
y1 = sin(x);
y2 = cos(x);
y3 = (sin(x)).^2;
y4 = (cos(x)).^2;
ymin = -1; ymax = 1; ystep = 0.2;
fig = figure("Units","normalized","Position",[0.1 0.1 0.5 0.75]);
ax1 = subplot(2,1,1);
plot(x,y1,'b-','DisplayName','y1','LineWidth',1)
ylabel('ylabel\_1L'); ylim([ymin ymax]); yticks(ymin:ystep:ymax);
yyaxis right;
plot(x,y2,'k--','DisplayName','y2','LineWidth',1);
ylabel('ylabel\_1R'); ylim([ymin ymax]); yticks(ymin:ystep:ymax);
xlabel('xlabel'); xlim([xmin xmax]); xticks(xmin:xstep:xmax); grid on
ax1.YAxis(1).Color = 'b'; ax1.YAxis(2).Color = 'k'; ax1.GridColorMode = "manual";
legend('Location','eastoutside'); title('graph 1')
ax2 = subplot(2,1,2);
hold on
plot(x,y3,'b-','DisplayName','y3','LineWidth',1)
plot(x,ones(length(x),1)*mean(y3),'-.','Color',[0 0 0.7],'DisplayName','Avg. y3')
ylabel('ylabel\_2L'); ylim([ymin ymax]); yticks(ymin:ystep:ymax);
yyaxis right;
plot(x,y4,'k--','DisplayName','Height');
ylabel('ylabel\_2R'); ylim([ymin ymax]); yticks(ymin:ystep:ymax);
xlabel('xlabel'); xlim([xmin xmax]); xticks(xmin:xstep:xmax); grid on
ax2.YAxis(1).Color = 'r'; ax2.YAxis(2).Color = 'k'; ax2.GridColorMode = "manual";
legend('Location','eastoutside'); title('graph 2')
annotation('textbox',[0.85 0.13 0.12 0.06],'BackgroundColor','w','String',sprintf('annotation 1\nannotation 2\nannotation 3'))
sgtitle('General title')
% pause(0.1)
ax2.Position(3) = ax1.Position(3);
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Mathematics en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
