how to add legend to plot in matlab

To add a legend to a plot in Matlab, you can use the built-in legend function. Here's an example:

main.m
% Create some example data
x = 1:10;
y1 = x.^2;
y2 = exp(x);

% Plot the data
plot(x, y1, 'b-', x, y2, 'r--')

% Add a legend
legend('y = x^2', 'y = e^x')
155 chars
11 lines

In this example, we first define some data (x, y1, and y2). We then use the plot function to create a figure with two curves (y1 and y2). Finally, we call legend and pass in two strings to label the curves. The first string corresponds to the blue curve, and the second string corresponds to the red curve.

You can customize the appearance of the legend by passing in additional arguments to the legend function. For example, if you want the legend to be positioned in the lower-right corner of the figure, you can use this code:

main.m
legend('y = x^2', 'y = e^x', 'Location', 'southwest')
54 chars
2 lines

The 'Location' argument specifies where the legend should be placed. Possible values include 'north', 'south', 'east', and 'west', as well as combinations like 'northeast' and 'southwest'.

related categories

gistlibby LogSnag