如何在 matlab 图形的 x 轴上重复相同的值?

How to repeat same values in x axis of matlab figures?

我有两个函数,它们的 'x' 在 1 和 30 之间 (1<=x<=30),每个函数都有自己的 'y'。我想将它们绘制在同一张图中并在它们之间画一条垂直线(将它们分开):

1<=x<=30 for function 1
x=31 separator
32<=x<=61 for function 2

这是代码:

y1=[6.5107   28.1239   15.0160   24.9586   17.6224   12.7936   21.9143    7.7560   27.4761    3.1279    8.3063   17.4207 8.3265    0.7540   13.2846   22.8183   25.7289   13.5553   18.0556   19.1853   20.2442    9.0290    5.3196    2.5757 21.6273    8.9054    2.0535    5.0569   22.7735   14.7483];
y2=[13.5876    5.7935    6.4742         0    7.7878         0    8.6912    0.4459   11.9369   10.4926    9.2844   10.4645 4.0736    9.0897    8.4051    0.7690   15.9073    3.7413    8.5098    9.7112    1.3231    8.5113    8.7681    4.1696 12.9530    0.6313   19.9750    0.0664    9.9677   10.1181];
%function 1
bar(1:30,y1,'r');
hold on
% a vertical line from x=31
plot([31 31],get(gca,'ylim'))
%function 2
bar(32:61,y2,'b');

但是当我绘制它们时,图中函数 1(左函数)的 x 轴是 1:30,图中函数 2(右函数)的 x 轴是 32:61 . 但我想将它们的 x 轴值显示为 1:30 而不是一个显示为 1:30 而另一个显示为 32:61。 (请参阅附件)。我怎样才能做到这一点?

我建议添加两行代码。您可以使用 set, gca, and xlim.

调整起始值和步长以获得您想要的美学效果
set(gca,'XTick',[0 2:2:61],'XTickLabel',[0 2:2:30 2:2:30])
xlim([0 62])

其他方法可能更有效,但希望这能让您继续前进。

正如评论中已经指出的那样,subplot 也可能工作得很好。

figure
s(1) = subplot(1,2,1)
b1 = bar(1:30,y1,'r');
s(2) = subplot(1,2,2)
b2 = bar(1:30,y2,'b');
title(s(1),'Function 1')
title(s(2),'Function 2')

% Cosmetics
xRng = [0 31];
yRng = [0 max(max(s(1).YLim),max(s(2).YLim))];
for k = 1:2
xlim(s(k),xRng)
s(k).YLim = yRng;   % Ensure both vertical axes are same (for fair comparison)
s(k).YGrid = 'on';
end

使用 MATLAB R2017a 测试

此答案与 的第二部分没有根本区别,但建议对 'cosmetics':

的一些改进技术
sp(1) = subplot(1,2,1);
bar(1:30,y1,'r');
sp(2) = subplot(1,2,2);
bar(1:30,y2,'b');
% set both y-axis to the same limits:
linkaxes(sp,'xy')
xlim([0 31])
sp(2).YTickLabel = [];
% tight the 2 subplots:
space = sp(2).Position(1)-sp(1).Position(1)-sp(1).Position(3);
sp(1).Position(3) = sp(1).Position(3)+0.5*space;
sp(2).Position(3) = sp(2).Position(3)+0.5*space;
sp(2).Position(1) = sp(2).Position(1)-0.5*space;
% create legend for both plots
legend([sp.Children],{'Function 1','Function 2'})