标记图,使标签与轴外的 ylabel 对齐
Labeling plots such that label is aligned with the ylabel outside the axes
请查看以下代码,它创建了一个 2 x 2 的子图,其中包含一些图:
x = linspace(0,2*pi);
y = sin(x);
hfig = figure('Position',[1317 474 760 729]);
subplot(2,2,1)
plot(x,y)
ylabel('plot1');
subplot(2,2,2)
plot(x,y.^2)
ylabel('plot2');
subplot(2,2,3)
plot(x,y.^3)
ylabel('plot3');
subplot(2,2,4)
plot(x,abs(y))
ylabel('plot4');
在每一个中,我都在工具中手动添加了标签:编辑图 (a) (b) (c) (d) 生成此图:
问题是,如果我调整图的大小,它们将不再与 ylabel 文本对齐:
有没有办法以编程方式添加这些标签并让它们自动与 ylabel 文本对齐?我很惊讶 MATLAB 没有内置这样的东西。
谢谢
如果不将侦听器附加到图形调整大小事件(参见 )并进行一些与纵横比相关的计算,这不是一件容易的事。
还不完全清楚你的标签是什么类型的对象(text
或 annotation
),所以我将只展示如何使用 text
命令以编程方式执行此操作,它在 axes 坐标 中创建标签(而不是 figure 坐标)。这并不能完全解决问题,但看起来更好,可能达到可以接受的程度:
function q56624258
x = linspace(0,2*pi);
y = sin(x);
hF = figure('Position',[-1500 174 760 729]);
%% Create plots
[hAx,hYL] = deal(gobjects(4,1));
for ind1 = 1:3
hAx(ind1) = subplot(2,2,ind1, 'Parent' , hF);
plot(hAx(ind1), x,y.^ind1);
hYL(ind1) = ylabel("plot" + ind1);
end
hAx(4) = subplot(2,2,4);
plot(hAx(4), x,abs(y));
hYL(4) = ylabel('plot4');
%% Add texts (in data coordinates; x-position is copied from the y-label)
for ind1 = 1:4
text(hAx(ind1), hYL(ind1).Position(1), 1.1, ['(' char('a'+ind1-1) ')'], ...
'HorizontalAlignment', 'center');
end
注意对代码的几处修改:
- 现在存储一些创建图形元素的函数返回的句柄(主要是:
hAx
、hYL
)。
- 所有创建图形元素(
subplot
、plot
、ylabel
)的函数现在都指定了目标(即父级或容器)。
- 我更改了图形的
'Position'
以便它在我的设置中工作(您可能想将其改回)。
请查看以下代码,它创建了一个 2 x 2 的子图,其中包含一些图:
x = linspace(0,2*pi);
y = sin(x);
hfig = figure('Position',[1317 474 760 729]);
subplot(2,2,1)
plot(x,y)
ylabel('plot1');
subplot(2,2,2)
plot(x,y.^2)
ylabel('plot2');
subplot(2,2,3)
plot(x,y.^3)
ylabel('plot3');
subplot(2,2,4)
plot(x,abs(y))
ylabel('plot4');
在每一个中,我都在工具中手动添加了标签:编辑图 (a) (b) (c) (d) 生成此图:
问题是,如果我调整图的大小,它们将不再与 ylabel 文本对齐:
有没有办法以编程方式添加这些标签并让它们自动与 ylabel 文本对齐?我很惊讶 MATLAB 没有内置这样的东西。
谢谢
如果不将侦听器附加到图形调整大小事件(参见
还不完全清楚你的标签是什么类型的对象(text
或 annotation
),所以我将只展示如何使用 text
命令以编程方式执行此操作,它在 axes 坐标 中创建标签(而不是 figure 坐标)。这并不能完全解决问题,但看起来更好,可能达到可以接受的程度:
function q56624258
x = linspace(0,2*pi);
y = sin(x);
hF = figure('Position',[-1500 174 760 729]);
%% Create plots
[hAx,hYL] = deal(gobjects(4,1));
for ind1 = 1:3
hAx(ind1) = subplot(2,2,ind1, 'Parent' , hF);
plot(hAx(ind1), x,y.^ind1);
hYL(ind1) = ylabel("plot" + ind1);
end
hAx(4) = subplot(2,2,4);
plot(hAx(4), x,abs(y));
hYL(4) = ylabel('plot4');
%% Add texts (in data coordinates; x-position is copied from the y-label)
for ind1 = 1:4
text(hAx(ind1), hYL(ind1).Position(1), 1.1, ['(' char('a'+ind1-1) ')'], ...
'HorizontalAlignment', 'center');
end
注意对代码的几处修改:
- 现在存储一些创建图形元素的函数返回的句柄(主要是:
hAx
、hYL
)。 - 所有创建图形元素(
subplot
、plot
、ylabel
)的函数现在都指定了目标(即父级或容器)。 - 我更改了图形的
'Position'
以便它在我的设置中工作(您可能想将其改回)。