Matlab:在图

时间:2015-08-21 10:49:14

标签: matlab matlab-figure

当我有一个带有两个x轴的图形时,我无法显示我的标题。 情节看起来不错,轴刻度正如我所希望的那样,但第二个轴标签和标题最终在我的图形之外。

如何让绘图和轴具有相同的大小并更改图形的大小以包含标签和标题?

这是一个最小的例子:

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');

1 个答案:

答案 0 :(得分:3)

作为一种解决方法,您可以在生成绘图之前预先定义第一个轴的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');

enter image description here

然后你可以随意调整大小;标题保持可见。

相关问题