Search code examples
matlabplotmatlab-figureerrorbar

Unable to plot `errorbar` work with `datetime` datatype in Matlab


I would like to plot errorbar with datetime on x-axis

x = datetime(['21-Aug-2019'; '22-Aug-2019'; '23-Aug-2019']);
y = [100; 110; 130];
figure
plot(x,y, '.')
hold on
errorbar(x, y, 20)

The final line produces this error- Error using errorbar (line 76) Input arguments must be numeric or objects which can be converted to double. Even the following produces error

errorbar(datenum(x), y, 20*ones(size(y)))

I am using R2016b


Solution

  • errorbar does not support datetime object. You can use datenum and datetick. datenum will convert your string vector containing your date into a double vector. Now that x is a double vector it can be used in errorbar.

    Finally convert your x label into human readable date format with datetick.

    x = datenum(['21-Aug-2019'; '22-Aug-2019'; '23-Aug-2019']);
    y = [100; 110; 130];
    
    figure
    hold on
    plot(x,y, '.')
    errorbar(x, y, [20;20;20])
    
    datetick('x','dd-mmm-YYYY')