Home > database >  Accumulating plot of data and fit in Matlab
Accumulating plot of data and fit in Matlab

Time:04-10

I have a Matlab script that imports data from a file and creates an exponential fit. I want the script to plot the data points and the fit using the same colour. The legend should be the name of the data file. When I run this same script again for another input file I want the new data and fit to be displayed in the same plot window name of the new data file added to the legend.

What I have so far is this;

expfit = fit(x,y,'exp1')

figure(1)
hold all
plot(x,y,'*','DisplayName','fileName)
legend('Interpreter','none')
legend show

using

plot(expfit,x,y,'DisplayName','fileName')

does not work

How can I add the fitted line to each data using the same colour as the data and adding the filenames to the legend ?

CodePudding user response:

You're close...

An easy way is to get the colours up front

c = parula(7); % default colour map with 7 colours

figure(1); clf;
hold on
% filename is a variable e.g. filename = 'blah.csv'; from where the data was loaded
plot( x, y, '*', 'DisplayName', filename, 'color', c(1,:) );
plot( expfit, x, y, '-', 'HandleVisibility', 'off', 'color', c(1,:) );
legend('show');

Note by setting HandleVisibility off the fit will not show up in the legend. This is personal preference, I only like one entry for the data and the fit, you could instead use the DisplayName on the 2nd plot too.

Both plots use the same colour using the color input. I've used the first row of the colour map for both, if you plotted some other data you could use the 2nd row etc.

The alternative is to let MATLAB determine the colour automatically and just copy the colour over for the 2nd plot, you need to create a variable (p) of the first plot to get the colour

p = plot( x, y, '*', 'DisplayName', filename );
plot( expfit, x, y, '-', 'HandleVisibility', 'off', 'color', p.Color );

The other code would be the same.

  • Related