matlabplotmatlab-figureerrorbarlinestyle

Errorbar line missing in Matlab


The following code produces the image shown:

    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

But, there should be a line connecting the datapoints. I even set the e1.LineStyle, but that didn't work. How can I produce that line?


Solution

  • You have no line because you don't plot vectors, but single values each time, which is why you get something that is closer to a scatter plot.

    Below are two of the ways to fix this:

    1. Solution 1 is a workaround that changes your existing code minimally.
    2. Solution 2 is much shorter code that achieves a same-looking result, by plotting vectors directly. (recommended).

    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.