Search code examples
matlabmatlab-figure

How can error bars be added to curve fitted scatter plots generated by MatLab's cftool?


I am trying to take a figure created using MatLab's cftool and add vertical error bars to the y data. I have been attempting to alter the auto-generated code which creates the figure.

I have tried using the errorbar function, but when I do so it overwrites the plot given. Namely, it creates a line plot (the dots should not be connected,) and the curve fit is also absent. I checked the documentation for the plot function, but there does not seem to be an option to add error bars to data.

function [fitresult, gof] = TungstenFit(Bin,Count,CountError)
[xData, yData] = prepareCurveData( Bin, Count );

% Set up fittype and options.
ft = fittype( 'b+m*x+A1*exp(-(x-u1)^2/(2*s1^2))+A2*exp(-(x-u2)^2/(2*s2^2))+A3*exp(-(x-u3)^2/(2*s3^2))', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.Lower = [0 0 0 0 -Inf -Inf -Inf -Inf 100 150 150];
opts.StartPoint = [850 500 50 0 -10 10 10 10 140 160 185];
opts.Upper = [Inf Inf Inf 10 Inf Inf Inf Inf Inf Inf Inf];

% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );

% Plot fit with data.
figure( 'Name', 'W3LsFit' );
h = plot( fitresult, xData, yData );
legend( h, 'Tungsten Bin Counts', 'W3LsFit', 'Location', 'NorthWest' );

% Label axes
xlabel Bin
ylabel Tungsten Bin Count
grid on

This code creates a scatter plot which contains the data and plots the curve fit function. However, it currently does nothing to the CountError data.

I am very new to MatLab (I had to teach it to myself for this assignment,) so any help or tips would be greatly appreciated. Thanks.


Solution

  • I have a working solution. For posterity, here is the code I added between creating a the plot and the legend function:

    hold on
    e = errorbar(xData,yData,CountError,'LineStyle','none');
    

    The first line causes the plot not to be overwritten, and the 'LineStyle','none' parameters causes errorbar function to add the error bars without drawing a line between the data points.