How to align both vertically and horizontally annotation box with legend box in plots?

26 visualizaciones (últimos 30 días)
I want to get the horizontal and vertical alignment of annotation box with the legend box to give simmetry to my plots.
Here is a reproducible example of my typical code I use to get these kind of plots:
clc;clear all; close all;
x= linspace(0,2*pi,1000);
y= sin(x-2);
plot(x,y)
legend('y=sin(x-2)');
grid on;
% Extra info box
dim = [.168 .80 .20 .06];
str = 'info box';
annotation('textbox',dim,'String',str,'Interpreter',"latex",'FitBoxToText','on',...
'BackgroundColor',[1 1 1],'FontSize',9);
Look at the following figure to better consider my problem: I want that the distances represented by the red segment are equal, and the same for the distances represented by the blue segments.
Can you help me to get these alignements?
Is there a way to give to "annotation" the same properties of legend command as "north, east, northwest, etc."?
  5 comentarios
Giuseppe
Giuseppe el 9 de Oct. de 2022
Thank you again. So, I think it's time to update to R2022b. I did not yet update because I'm very busy with my thesis.
Because of bad experience with a Microsoft Visual studio update, I'm a little bit afraid when there is a new update to do.
Star Strider
Star Strider el 9 de Oct. de 2022
My pleasure!
I was referring to R2022a updates (top toolstrip: RESOURCES —> Help —> Check for Updates), however I definitely recommend R2022b.
I have rarely had problems with MATLAB interim updates, and upgrades to new releases. A few years ago, one new release failed to import my preferences and that required about an extra half hour of work to get those imported, however the others have gone seamlessly.

Iniciar sesión para comentar.

Respuesta aceptada

Simon Chan
Simon Chan el 1 de Oct. de 2022
"annotation" dose not have properties of legend command as north, east,...
I think you may need to calculate the margin separately as follows:
x= linspace(0,2*pi,1000);
y= sin(x-2);
plot(x,y)
ax=gca;
lgd=legend('y=sin(x-2)');
grid on;
% Extra info box
dim = [.168 .80 .20 .06];
str = 'info box';
an=annotation('textbox',dim,'String',str,'Interpreter',"latex",'FitBoxToText','on',...
'BackgroundColor',[1 1 1],'FontSize',9);
%% Calculate the required margins
newx = ax.InnerPosition(1)+ax.InnerPosition(3)-(lgd.Position(1)+lgd.Position(3))+ax.InnerPosition(1);
newy = lgd.Position(2)+lgd.Position(4)-an.Position(4);
set(an,'Position',[newx newy an.Position(3) an.Position(4)]);
  5 comentarios
Simon Chan
Simon Chan el 8 de Oct. de 2022
I try to add "axis equal" and the result looks aceptable (Visually check).
I suggest to use "normalized" instead of "pixels" as the Units for all objects incuding the axis itself.
x= linspace(0,2*pi,1000);
y= sin(x-2);
plot(x,y)
ax=gca;
axis(ax,'equal'); % <--Axis equal added here
lgd=legend('y=sin(x-2)');
grid on;
% Extra info box
dim = [.168 .80 .20 .06];
str = 'info box';
an=annotation('textbox',dim,'String',str,'Interpreter',"latex",'FitBoxToText','on',...
'BackgroundColor',[1 1 1],'FontSize',9);
%% Calculate the required margins
newx = ax.InnerPosition(1)+ax.InnerPosition(3)-(lgd.Position(1)+lgd.Position(3))+ax.InnerPosition(1);
newy = lgd.Position(2)+lgd.Position(4)-an.Position(4);
set(an,'Position',[newx newy an.Position(3) an.Position(4)]);
Giuseppe
Giuseppe el 9 de Oct. de 2022
Editada: Giuseppe el 9 de Oct. de 2022
Hi @Simon Chan I did several attempts but with no succes!
Can you take a look at my code:
load UHIM_DB_light.mat
load Customized_colors
num_orbits = 2; % Number of orbits for each value of JC
num_orbit_points = 200; % Number of points for each orbit
array_manif_idx = 1:1:numel(UHIM_DB(1).data(1).PLO_to_CI);
idx_manif_traj = 1;
% Matrix containing 200 HIM trajectories (200 points for each trajectory)
matrix_traj_idx = reshape(array_manif_idx,[num_orbit_points,num_orbits]) ;
indices_Manif_traj = matrix_traj_idx(:,idx_manif_traj);
mu = 3.040423426440150e-06;
idx_JC = 3;
factor_k = 2;
au2km = 1.495978707e+08;
r_Laplace_SOI=9.29e+05;
rCI_EM_km = factor_k .* r_Laplace_SOI;
fig = figure;
hold on; axis equal; grid on; box on;
traj_colors = [1 0.3 0.3;0.3 0.8 0.9];
txt_pts_offset =[+0.1e+6,+0.9e+5;+0.1e+6,-0.3e+6];
text_pos =[-0.0012,-0.0025;-0.00075,-0.0025];
r_CI_lgd = ['$r_{CI} =\ $',num2str(rCI_EM_km,'%3.2e'),'$\ km$'];
% Plot CI
CI_plot=plotCircle((mu-1)*au2km,0*au2km,rCI_EM_km,[0 1 0],0.7,r_CI_lgd);
num_L_points = 2;
colors_PLO = [my_red;my_blue];
traj_plot = zeros(1,numel(num_L_points)); % preallocation
% Plot trajectories of unstable manifold
for idx_L=1:num_L_points
lgd_label = ['$JC =\ $',num2str(UHIM_DB(idx_L).data(idx_JC).JC,'%9.6f')];
% Plot PLOs
plot([UHIM_DB(idx_L).data(idx_JC).PLO.x]*au2km,[UHIM_DB(idx_L).data(idx_JC).PLO.y]*au2km,...
'--','Color',colors_PLO(idx_L,:),'LineWidth',1.0);
% Plot trajectories
manif_traj = UHIM_DB(idx_L).data(idx_JC).PLO_to_CI(indices_Manif_traj);
traj_plot(idx_L)=plot([manif_traj.x]*au2km,[manif_traj.y]*au2km,...
'Color',traj_colors(idx_L,:),'LineWidth',0.5,'DisplayName',lgd_label);
% Plot initial point
pt_I = [[manif_traj(1).x]*au2km,[manif_traj(1).y]*au2km];
plot(pt_I(1),pt_I(2),'.','Color',[0 0 0],'LineWidth',0.3);
text(pt_I(1)+txt_pts_offset(idx_L,1),pt_I(2),'$I$',...
'Interpreter',"latex",'Color',[0 0 0],'FontSize',8);
% Plot final point
pt_F = [[manif_traj(end).x]*au2km,[manif_traj(end).y]*au2km];
plot(pt_F(1),pt_F(2),'.','Color',[0 0 0],'LineWidth',0.3);
text(pt_F(1)+txt_pts_offset(idx_L,2),pt_F(2),'$F$',...
'Interpreter',"latex",'Color',[0 0 0],'FontSize',8);
end
hold off
% Axes lables
xlabel('$x$ (km)','interpreter','latex','fontsize',12);
ylabel('$y$ (km)','interpreter','latex','FontSize',12);
ax=gca;
%Legend
lgd = legend([traj_plot,CI_plot],'Orientation',"vertical",'Location',"northeast");
lgd.Interpreter = 'latex';
lgd.FontSize = 8;
% Extra information box
dim = [0.23 0.815 .150 .06];
str = ['$Epoch_I = t_0 $',newline,...
'$Epoch_F = t_0\ + \Delta_{t\ CI} $'];
an=annotation('textbox',dim,'String',str,'Interpreter',"latex",'FitBoxToText','on',...
'BackgroundColor',[1 1 1],'FontSize',8,...
'HorizontalAlignment','left','VerticalAlignment','bottom');
%% Calculate the required margins
newx = ax.InnerPosition(1)+ax.InnerPosition(3)-(lgd.Position(1)+lgd.Position(3))+ax.InnerPosition(1);
newy = lgd.Position(2)+lgd.Position(4)-an.Position(4);
set(an,'Position',[newx newy an.Position(3) an.Position(4)]);
% Option to center better the curves inside the plot window
x_lim = xlim; y_lim = ylim;
xlim([x_lim(1)-0.005*norm(x_lim) x_lim(2)+0.005*norm(x_lim)]);
ylim([y_lim(1)-0.1*norm(y_lim) y_lim(2)+0.3*norm(y_lim)]);
JC_id = ['$JC\ index =\ $',num2str([UHIM_DB(idx_L).data(idx_JC).idx_Jacobi_cst])];
traj_index = ['$traj.\ index =\ $',num2str(idx_manif_traj)];
title([JC_id,', ',traj_index],'Interpreter','latex');
%set(gcf,'position',[400, 200, 560, 315]); %Aspect ratio: 16/9
set(gcf,'position',[278.6, 0.2, 600, 400]); %aspect ratio 3/2
%exportgraphics(fig,'fig_UHIM_test.pdf','ContentType','vector'); %salva in pdf
%exportgraphics(fig,'fig_UHIM_test.png','Resolution',600); %salva in jpeg
If you try to export the figure, you can see that the horizontal alignment of the annotation box is wrong.
My output is shown below (You can see more details that I removed from the above code to simplify it):

Iniciar sesión para comentar.

Más respuestas (0)

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by