Matlab:在图中拟合两个 x 轴和一个标题
Matlab: Fitting two x axis and a title in figure
当我有一个包含两个 x-axis 的图形时,我无法显示我的标题。
情节看起来不错,轴比例符合我的要求,但第二个轴标签和标题最终超出了我的图。
如何使绘图和轴具有相同的大小并更改图的大小以包含标签和标题?
这是一个最小的例子:
x1 = linspace(0, 5);
y11 = sin(x1);
y12 = cos(x1);
x2 = linspace(4, 12);
figure(1)
plot(x1, y11, 'r');
hold on
grid on
plot(x1, y12, 'k');
axis([0 5 -1 1.8]);
legend('sin(x)', 'cos(x)');
xlabel('x')
ylabel('y-label');
ax1 = gca;
ax1_pos = ax1.Position;
ax2 = axes('Position', ax1_pos,...
'XAxisLocation', 'top',...
'YAxisLocation', 'right',...
'Color', 'none');
ax2.YColor = 'w';
title('2:nd Harmonics');
line(x2,0,'Parent',ax2,'Color','k')
xlabel('n');
作为解决方法,您可以在生成图之前 pre-define 第一个轴的 Position
属性(即大小),这样即使您添加第二个轴,标题也能正确显示轴。例如,在调用 figure(1)
后立即添加如下内容:
ax1 = axes('Position',[0.11 0.11 0.75 0.75]);
此外,如果您希望在标题中打印指数值,您可以使用 Latex 格式,如下所示:
title('2^{nd} Harmonics');
这是带有输出的完整代码:
clear
clc
close all
x1 = linspace(0, 5);
y11 = sin(x1);
y12 = cos(x1);
x2 = linspace(4, 12);
figure(1)
%// Set axes position manually
ax1 = axes('Position',[0.11 0.11 0.75 0.75]);
plot(x1, y11, 'r');
hold on
grid on
plot(x1, y12, 'k');
axis([0 5 -1 1.8]);
legend('sin(x)', 'cos(x)');
xlabel('x')
ylabel('y-label');
%ax1 = gca;
ax1_pos = get(ax1,'Position');
ax2 = axes('Position', ax1_pos,...
'XAxisLocation', 'top',...
'YAxisLocation', 'right',...
'Color', 'none');
set(ax2,'YColor','w');
%// Notice the Latex formatting to print the exponent
title('2^{nd} Harmonics');
line(x2,0,'Parent',ax2,'Color','k')
xlabel('n');
然后你可以随意调整大小;标题保持可见。
当我有一个包含两个 x-axis 的图形时,我无法显示我的标题。 情节看起来不错,轴比例符合我的要求,但第二个轴标签和标题最终超出了我的图。
如何使绘图和轴具有相同的大小并更改图的大小以包含标签和标题?
这是一个最小的例子:
x1 = linspace(0, 5);
y11 = sin(x1);
y12 = cos(x1);
x2 = linspace(4, 12);
figure(1)
plot(x1, y11, 'r');
hold on
grid on
plot(x1, y12, 'k');
axis([0 5 -1 1.8]);
legend('sin(x)', 'cos(x)');
xlabel('x')
ylabel('y-label');
ax1 = gca;
ax1_pos = ax1.Position;
ax2 = axes('Position', ax1_pos,...
'XAxisLocation', 'top',...
'YAxisLocation', 'right',...
'Color', 'none');
ax2.YColor = 'w';
title('2:nd Harmonics');
line(x2,0,'Parent',ax2,'Color','k')
xlabel('n');
作为解决方法,您可以在生成图之前 pre-define 第一个轴的 Position
属性(即大小),这样即使您添加第二个轴,标题也能正确显示轴。例如,在调用 figure(1)
后立即添加如下内容:
ax1 = axes('Position',[0.11 0.11 0.75 0.75]);
此外,如果您希望在标题中打印指数值,您可以使用 Latex 格式,如下所示:
title('2^{nd} Harmonics');
这是带有输出的完整代码:
clear
clc
close all
x1 = linspace(0, 5);
y11 = sin(x1);
y12 = cos(x1);
x2 = linspace(4, 12);
figure(1)
%// Set axes position manually
ax1 = axes('Position',[0.11 0.11 0.75 0.75]);
plot(x1, y11, 'r');
hold on
grid on
plot(x1, y12, 'k');
axis([0 5 -1 1.8]);
legend('sin(x)', 'cos(x)');
xlabel('x')
ylabel('y-label');
%ax1 = gca;
ax1_pos = get(ax1,'Position');
ax2 = axes('Position', ax1_pos,...
'XAxisLocation', 'top',...
'YAxisLocation', 'right',...
'Color', 'none');
set(ax2,'YColor','w');
%// Notice the Latex formatting to print the exponent
title('2^{nd} Harmonics');
line(x2,0,'Parent',ax2,'Color','k')
xlabel('n');
然后你可以随意调整大小;标题保持可见。