在 MATLAB 中突出显示图形的特定部分

Highlight specific section of graph in MATLAB

我希望 highlight/mark 通过在 MATLAB 中绘制数组的某些部分。经过一些研究 (like here),我尝试保留第一个图,找到突出显示的索引,然后是一个新图,只有这些点。但是,正在绘制这些点,但都移到了轴的开头:

我目前正在尝试使用此代码:

load consumer;   % the main array to plot (157628x10 double) - data on column 9
load errors;     % a array containing the error indexes (1x5590 double)

x = 1:size(consumer,1)';      % returns a (157628x1 double)
idx = (ismember(x,errors));   % returns a (157628x1 logical)

fig = plot(consumer(:,9));
hold on, plot(consumer(idx,9),'r.');
hold off

我想做的另一件事是突出显示图表的整个部分,就像在相同部分上的 "patch"。有什么想法吗?

问题在于您只向 plot 函数提供了 y 轴数据。默认情况下,这意味着所有数据都绘制在绘图的 1:numel(y) x 位置,其中 y 是您的 y 轴数据。

您有 2 个选择...

  1. 同时提供 x 轴数据。反正你已经得到了数组 x

    figure; hold on;
    plot(x, consumer(:,9));
    plot(x(idx), consumer(idx,9), 'r.');
    

    旁白:我有点不明白你为什么要创建 idx。如果 errors 如您所描述的那样(数组的索引),那么您应该只能使用 consumer(errors,9).

  2. 让所有不想出现的数据都等于NaN。由于您加载错误索引的方式,这不是那么快速和容易。基本上你会将 consumer(:,9) 复制到一个新变量中,并索引所有不需要的点以将它们设置为等于 NaN.

    这种方法也有打破不连续部分的好处。

    y = consumer(:,9);          % copy your y data before changes
    idx = ~ismember(x, errors); % get the indices you *don't* want to re-plot
    y(idx) = NaN;               % Set equal to NaN so they aren't plotted
    
    figure; hold on;
    plot(x, consumer(:,9));
    plot(x, y, 'r');            % Plot all points, NaNs wont show