Coding Ref

How to plot a legend in MATLAB

How to plot a legend in MATLAB

In MATLAB, a legend is a component of a graph that provides a description of the plotted data. A legend typically consists of a list of labels, one for each data series in the plot, and a marker or symbol that identifies the data series on the graph.

To add a legend to a plot in MATLAB, you can use the legend function. The legend function takes a cell array of strings as an argument, where each string represents the label for a data series.

For example, to add a legend to a line plot with two data series, you could use the following commands:

x = 0:0.1:10;
y1 = sin(x);
y2 = cos(x);
plot(x, y1)
hold on
plot(x, y2)
legend({'sin(x)', 'cos(x)'})

The legend function places the legend on the graph in a default location. You can specify the location of the legend using the 'Location' property. The location can be specified using a string (e.g. 'northwest', 'southwest', etc.) or a numeric value (e.g. 1, 2, 3, etc.).

Here is an example that places the legend in the upper left corner of the graph:

x = 0:0.1:10;
y1 = sin(x);
y2 = cos(x);
plot(x, y1)
hold on
plot(x, y2)
legend({'sin(x)', 'cos(x)'}, 'Location', 'northwest')

Adding a title to a legend

You can also add a title to a legend in MATLAB using the 'Title' property. The 'Title' property specifies a string that is used as the title of the legend.

Here is an example that adds a title to the legend:

x = 0:0.1:10;
y1 = sin(x);
y2 = cos(x);
plot(x, y1)
hold on
plot(x, y2)
legend({'sin(x)', 'cos(x)'}, 'Location', 'northwest', 'Title', 'Trigonometric Functions')

Conclusion

To add a legend to a plot in MATLAB, you can use the legend function. The legend function takes a cell array of strings as an argument, where each string represents the label for a data series.

You'll also like

Related tutorials curated for you

    How to create a scatter plot in MATLAB

    Plot markers in MATLAB

    How to plot a line in MATLAB

    How to plot colors in MATLAB

    MATLAB subplot

    How to create a surface plot in MATLAB

    How to plot a Bode in MATLAB

    How to create a 3D plot in MATLAB

    MATLAB linspace

    How to plot points in MATLAB

    How to plot a legend in MATLAB