MATLAB Programming/Inserting Newlines into Plot Labels

From Wikibooks, open books for an open world
< MATLAB Programming
Jump to: navigation, search

Cell arrays are the easiest way to generate new lines when using the functions xlabel, ylabel, zlabel, text, title, and gtext. However, cell arrays do not always work (see next section).

When displaying text on plots, "\n" is typically interpreted as '\' followed by 'n' instead of the newline character. To generate multiple lines, use cell arrays. This is done by separating each string line of text with a comma and enclosing all comma-separated strings in curly braces as follows.

>> title({'First line','Second line'})

Sometimes it is nice to put the value of a variable and a newline into the plot title. You can do this like so:

n = 4;
x = -n:1:n;
y = x.^2;
title( [ 'plot of x squared', 10, 'from x = ', num2str(-n), ' to x = ', num2str(n) ] )

The 10 outside the single quotes is the ascii value for a newline. You don't have to use the char() function, just the number will work.

The output should look like this:

plot of x squared
from x = -4 to x = 4