How to Draw Line in Plot Matlab

Plot legends are essential for properly annotating your figures. Luckily, MATLAB/Octave include the legend() function which provide some flexible and easy-to-use options for generating legends. In this article, I cover the basic use of the legend() function, as well as some special cases that I tend to use regularly.

The source code for the included examples can be found in the GitHub repository.

Basic Use of Plot Legends

The legend() function in MATLAB/Octave allows you to add descriptive labels to your plots. The simplest way to use the function is to pass in a character string for each line on the plot. The basic syntax is: legend( 'Description 1', 'Description 2', … ).

For the examples in this section, we will generate a sample figure using the following code.

          x = 0 : 0.1 : ( 2pi );  plot( x, sin( x ), 'rx', 'linewidth', 2 );  hold on;  plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2 );  plot( x, cos( 4x )/3, '^g', 'linewidth', 2 ); hold off; xlim( [ 0, 2*pi ] ); grid on; title( 'Sample Plot' ); set( gca, 'fontsize', 16 );        

A legend can be added with the following command.

          legend( 'Line 1', 'Line 2', 'Line 3' );        

In addition to specifying the labels as individual character strings, it is often convenient to collect the strings in a cell array. This is most useful when you are programmatically creating the legend string.

          legStr = { 'Line 1', 'Line 2', 'Line 3' }; legend( legStr );        

For convenience, this method will be used for the rest of the examples. The resulting figure looks like this.

Image by author

By default the legend has been placed in the upper, right corner; however, the 'location' keyword can be used to adjust where it is displayed. The location is selected using a convention based on the cardinal directions. The following keywords can be used: north, south, east, west, northeast, northwest, southeast, southwest. The following code snippet would place the legend in the center top of the plot.

          legend( legStr, 'location', 'north' );        

Similarly, all of the other keywords can be used to place the legend around the plot. The following animation illustrates all of the different keywords.

Image by author

The keyword 'outside' can also be appended to all of the locations to place the legend outside of the plot. The next image shows an example with the legend on the east outside.

          legend( legStr, 'location', 'eastoutside' );        

In addition to the setting the location, the legend() function also allows you to set the orientation of the legend to either 'vertical' (default) or 'horizontal'. The following example will position the legend at the bottom, outside of the plot, with a horizontal orientation.

          legend( legStr, 'orientation', 'horizontal', ...   'location', 'southoutside' );        
Image by author

Using the "DisplayName" Property

Another convenient way to add the legend labels is to set the "DisplayName property on the lines as they are plotted. This can be done during the plot() call or using set() on the handle. In both cases, after you have set the properties, you need to all legend() without any arguments to toggle the legend on.

The syntax for the plot() should look like this.

          plot( x, sin( x ), 'rx', 'linewidth', 2, 'DisplayName', 'Line1' ); hold on; plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2, 'DisplayName', 'Line2' ); plot( x, cos( 4*x )/3, '^g', 'linewidth', 2, 'DisplayName', 'Line3' ); hold off;        

The syntax for the set() should like this.

          % Plot the lines h1 = plot( x, sin( x ), 'rx', 'linewidth', 2, 'DisplayName', 'Line1' ); hold on; h2 = plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2, 'DisplayName', 'Line2' ); h3 = plot( x, cos( 4*x )/3, '^g', 'linewidth', 2, 'DisplayName', 'Line3' ); hold off;  % Update the display names set( h1, 'DisplayName', 'Line1' ); set( h2, 'DisplayName', 'Line2' ); set( h3, 'DisplayName', 'Line3' )        

The legend would then be toggled on by calling legend() without any input arguments.

          legend();        

The resulting plot would be the same as the first example shown earlier in the tutorial.

Using the Legend Handle

Similar to all of the other graphics objects, the legend properties can be adjusted using the set() and get() functions. The following code will capture the legend handle and then set a few of the legend properties. In this particular example, the location is set to northeast, the orientation is set to vertical, the font size is set to 16, and the box outline is removed.

          hl = legend( legStr );     % save the legend handle set( hl, 'orientation', 'vertical' );     % set the orientation set( hl, 'location', 'northeast' );     % set the location set( hl, 'fontsize', 16 );     % set the font size set( hl, 'box', 'off' );    % turn off the box lines        
Image by author

There are number of other properties that can be set on the legend object. Simply call get(hl) in the command window to display them all. One of the most convenient of these properties is the 'position' property. The position property allows us to set the exact position of the legend by specifying its horizontal origin (h0), vertical origin (v0), width (w) and height (h). If you are not familiar with setting the position property on graphics object, you can see a brief description here.

Whenever you are working with subplots or GUIs, it is often necessary to specify an exact location for the legend. This ensures that your legend does overlap with other elements or create weird spacing. Building on the previous example, we can mock up an example GUI that includes our plot, a couple of buttons, and a legend that is manually placed on the figure.

          % Set up the subplot set( f, 'units', 'normalized' ); a = subplot( 'position', [ 0.1, 0.1, 0.5, 0.8 ] );  % Build our sample plot x = 0 : 0.1 : ( 2*pi ); plot( x, sin( x ), 'rx', 'linewidth', 2 ); hold on; plot( x, cos( x/3 ) - 0.25, 'bs', 'linewidth', 2 ); plot( x, cos( 4*x )/3, '^g', 'linewidth', 2 ); hold off; xlim( [ 0, 2*pi ] ); grid on; title( 'Sample Plot' ); set( a, 'fontsize', 16 );  % Add some buttons a = uicontrol( f, 'units', 'normalized', 'position', [ 0.7, 0.7, 0.2, 0.1 ], ...   'style', 'pushbutton', 'string', 'Press Me' ); a = uicontrol( f, 'units', 'normalized', 'position', [ 0.7, 0.5, 0.2, 0.1 ], ...   'style', 'pushbutton', 'string', 'Click Here' );  % Add a legend manually hl = legend( legStr ); set( hl, 'fontsize', 16 ); set( hl, 'position', [ 0.74   0.25   0.12721   0.14310 ] );        
Image by author

Adding Specific Lines to the Legend

Rather than providing character strings for all of the lines on the plot, it is possible to specify an array of specific line objects that should be included in the legend. I find this especially useful for situations where you only need to draw attention to a few lines on the plot. I tend to use this feature when I am plotting a large number of examples or realizations of some kind and want to overlay and highlight some statistics or metrics.

The following example creates some random data and calculates some statistics from it. All of the realizations are plotted as thin gray lines and the statistics are overlaid as much thicker colored lines.

          % Generate some random data and calculate a few statistics t = sqrt( 0.5 ) * randn( 100, 500 ); ts = sort( t, 2 ); t10 = ts( :, floor( 0.10 * size( t, 2 ) ) ); t90 = ts( :, floor( 0.90 * size( t, 2 ) ) );  % Plot realizations as thin gray lines and statistics as thicker, colored lines plot( t, 'linewidth', 0.2, 'color', [0.5 0.5 0.5] ); hold on; l1 = plot( mean( t, 2 ), 'linewidth', 4, 'color', [0, 1, 0] ); l2 = plot( t10, 'linewidth', 4, 'color', [1, 0, 0] ); l3 = plot( t90, 'linewidth', 4, 'color', [0, 0, 1] ); hold off; grid on; ylim( [-3, 3] ); title( 'Statistics' ); set( gca, 'fontsize', 16 );  % Add a legend to just the statistics hl = legend( [ l1, l2, l3 ], 'Mean', '10th Prct', '90th Prct', ...   'orientation', 'horizontal', 'location', 'north' ); set( hl, 'fontsize', 16 );        
Image by author

The result is a pretty nice plot (in my opinion). If we didn't pass in the line handles, then the legend() function would have tried to add a legend label to every single realization. There are certainly other use cases; however, this is a type of plot that I tend to make pretty frequently.

Summary

In this article, I covered several ways to use the legend() function in MATLAB/Octave. Here are few key things to remember.

  • The legend labels can be passed in as individual character strings or as a cell array.
  • There a number of both position and orientation options that can be used to place the legend in certain parts of the figure.
  • The legend graphics handle can be used to directly set any of the legend properties, including manually setting the position anywhere in the figure.
  • Line graphics handles can be used to specify a subset of lines that will be labeled in the legend.

Happy coding!

How to Draw Line in Plot Matlab

Source: https://thinkdata.science/?p=192

0 Response to "How to Draw Line in Plot Matlab"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel