Matlab中缺少Errorbar行

时间:2016-11-23 12:51:30

标签: matlab plot matlab-figure errorbar linestyle

以下代码生成显示的图像:

    probabilities = datasetlist(1,:);
    avgscores = datasetlist(2,:);
    x = probabilities;
    y = probabilities;
    err = avgscores;
    hold on
    for k = 1:length(x)
        e1 = errorbar(x(k),y(k),err(k),'-');
        if err(k) == min(err)
            set(e1,'Color','r')
            set(e1,'MarkerEdgeColor','r') 
            set(e1,'Marker','*')
        else
            set(e1,'Color','k')
            set(e1,'MarkerEdgeColor','k')
            set(e1,'Marker','.')
        end
    end
    hold on
    e1.LineStyle = '-';

enter image description here

但是,应该有一条连接数据点的线。我甚至设置了e1.LineStyle,但这并没有奏效。我怎样才能产生那条线?

1 个答案:

答案 0 :(得分:1)

你没有线,因为你没有绘制矢量,而是每次都是单个值,这就是你得到更接近scatter图的原因。

以下是解决此问题的两种方法:

  1. Solution 1是一种解决方法,可以最低限度地更改现有代码。
  2. Solution 2是通过直接绘制向量来实现相同结果的更短的代码。 (推荐)。
  3. function q40765062
    %% Prepare the data:
    datasetlist = [0.4:0.05:0.7; abs(randn(1,7))];
    probabilities = datasetlist(1,:);
    avgscores = datasetlist(2,:);
    x = probabilities;
    y = probabilities;
    err = avgscores;
    
    %% Solution 1:
    figure();
    hold on
    for k = 1:length(x)
        e1 = errorbar(x(k),y(k),err(k),'-');
        if err(k) == min(err)
            set(e1,'Color','r')
            set(e1,'MarkerEdgeColor','r') 
            set(e1,'Marker','*')
        else
            set(e1,'Color','k')
            set(e1,'MarkerEdgeColor','k')
            set(e1,'Marker','.')
        end
    end
    plot(x,y,'-k'); % < The main difference in this solution.
    
    %% Solution 2:
    figure(); 
    [~,I] = min(err); % < We compute the index of the minimal value before plotting anything.
    errorbar(x,y,err,'-*k'); hold on; % < Notice how we use the entire vectors at the same time.
    errorbar(x(I),y(I),err(I),'-*r'); % < We only plot one value this time; in red.