MATLAB:如何自定义非线性 X 轴(例如在 1,2,3,4,5,20,100,'string' 处刻度)

MATLAB: how to customize non linear X axis (for example ticks at 1,2,3,4,5,20,100,'string')

我正在使用 MATLAB 绘图功能比较两个向量。我希望我的 X 轴表示 1 到 7,然后是 14、21,最后是 X 值未确定的点的类别。(我也不确定如何表示这些无数点(它们有 Y值,只是没有 X 值)我可以为这些点分配任何 X 值 (1000) 之外的大数字,执行 1-7,14,21,1000,然后将 1000 标签更改为我的 'string for un-numbered points' . ??

这是一种基于 The Mathworks here 示例的方法。

诀窍是创建 2 个具有不同范围的 x 轴,并使其中之一透明。然后您可以使用它的属性。我修改了一些他们的代码,但保留了他们的大部分评论,因为他们很好地解释了这些步骤。

对于演示,我使用 scatter 来表示点,并将 "good" 点涂成红色,将另一个点(此处只有 1 个)涂成绿色。您当然可以自定义所有这些。例如,我为第二个轴的 x 值使用了 100 而不是 1000,但我会让你弄清楚如何修改它以根据需要更改输出。

clear
clc
close all

%// Create axes 1 and get its position
hAxes1 = axes;
axes_position = get(hAxes1, 'Position');

%// Create axes 2 and place it at the same position than axes 1
hAxes2 = axes('Position', axes_position);

%// Your data go here.
x = [1 7 14 21 100];
y = rand(1, length(x));

%// Plot the two sections of data on different axes objects

hPlot1 = scatter(hAxes1, x(1:4), y(1:4),40,'r','filled');
hold on
hPlot2 = scatter(hAxes2, x(end), y(end),40,'g','filled');

%// Link the y axis limits and fontsize property of the axes objects

linkaxes([hAxes1 hAxes2], 'y');
linkprop([hAxes1 hAxes2], 'FontSize');

%// Set the x range limits and tick mark positions of the first axes object
set(hAxes1, 'XLim', [1 25], ...
      'XTick', [1 7 14 21])
%// Set the x range limits and tick mark positions for the second axes object.
%// Also set the background color to 'none', which makes the background
%// transparent.Add the label for the "super points".

set(hAxes2, 'Color', 'none', ...
      'YTickLabel', [], ...
      'XLim', [95 100], ...
      'XTick', 100,'XTickLabel',{'Super Points'})

输出:

编辑

如果你想添加一条拟合线,我建议在与其他 2 个轴相同的位置添加第 3 个轴,使其透明并删除它的 X- 和 Y-ticks。

即添加如下内容:

hAxes3 = axes('Position', axes_position,'Color','none','YTick',[],'XTick',[]);

并且在对 polyfit/polyval 的调用中,在我的示例中您只想获取前 4 个元素(即红色元素)。

因此:

p = polyfit(x(1:4),y(1:4),1);
y_poly = polyval(p,x(1:4));

然后在 hAxes3 上画线:

hPlot3 = plot(x(1:4),y_poly)

输出: