Example for creating a plot in MATLAB

In which I attempt to tell what I know about creating plots using MATLAB via an example.

[Back to main page] [Back to plot page]

First, some philosophy on making plots in MATLAB....

I divide the scientific plots I make into two basic categories:

In either case, I find it is very useful to create a script Mfile to create the plot rather than just banging the plot out at the command line.


  1. Because I am lazy make mistakes. (... as you can see!)

    If a plot is even moderately complicated, the sequence of events that lead to its creation may be more than my brain (or my typing skills) can handle. I need a way to correct errors without having to mindlessly re-type commands. This is especially critical when my editting takes place over more than one session of using MATLAB.

  2. I like to have a record of how I created a particular plot, particularly if there is important data or analysis of data that is involved.

    Documentation is an important aspect in the engineering profession and computer "codes" (whether scripts or macros or full-blown compiled libraries) are part of an engineers professional life that must be kept track of at all times. Leaving out the details of a plot can sometimes lead to questions as to the truth of the results presented in a plot. That is not a result I am after.

Hence, in this example, I will encourage you to create a plot by creating an Mfile that you can execute as many times as needed to "tweak" to your heart's delight.

Step 0: Get MATLAB ready

Make sure MATLAB is started. Open a new file in the editor. You should be able to cut and paste commands directly from this page into that file so it should be pretty easy (I hope) to get results in a short period of time. If not let me know.

Step 1: Start with a clean slate

Whenever possible, I start with a clear-ed MATLAB workspace. If I am really interested in starting from the lowest level, I will close all open figures. Hence, I start with the lines

   % An Mfile to display plot creation
   clear       % always
   close all   % maybe not always

If you use close all, you will get rid of existing figures. An alternative is to use the command

   figure      % create a new sheet of paper

to add a new plot to the screen. Use what works for you.

Step 2: Bring in data or define important parameters

If your plot involves some sort of measured data, load that data into the workspace. If your plot is to display numerical results from a model, perhaps you would want to set some parameters for the model and then run the model and plot the results. The point is to keep the basic data of the figure as close to the creation of the figure as possible. Think algorithm!

In this example, I'll combine the two ideas.

   % create a set of synthetic data
   omega = 2;                            
   t = linspace(0,10,34);               
   y = 4*sin(omega*t) + randn(size(t));  % data
   % Some modelling parameters
   amp = 3.9;
   w = 2.1;
   phase = .1;
   ypred = amp*sin(w*t + phase);       % Model is "executed" for comparisons

   % Show the full prediction, not just at the data points
   tfit = linspace(min(t),max(t),20);  % is this good enough?
   yfit = amp*sin(w*tfit + phase);     % Model is "executed" for display

From a documentation point of view, it is very clear what is going on here (i.e., the algorithm is explicit and little is hidden). That's a Very Good Thing.

Step 3: Execute the plot

In this example, the plot is meant to compare a model (and its associated parameters) to some data. I would like to quantify the comparison and the sum of the squares of the residuals (errors) is one way to do that (there are others). Including the SSE information in the title is also a good thing.

   err = y - ypred;
   sse = sum(err.^2);
   str = ['Comparison for omega = ',num2str(w),' : SSE = ',num2str(sse)];
   xlabel('Time, sec')
   ylabel('Detector output, meters^{-1}')

I did the title in two lines because that was clearer to me. You can make lots of little errors creating the strings in a hurry.

Step 4: Edit, fix and improve

No one is perfect and either there are errors in the code or the result is not what you want (more often the case than not). However, you have the commands needed to make the plot so it's really not that bad. Some edits, some changes, a save, another execute and you are off to see what happens next. Yes, you might encounter frustrating syntax errors but you are avoiding them as you correct them.

After you have corrected syntax errors, you might try some of the things from the plotting tips page, like

Step 5: Admire and use your work

Congratualtions! You have a well done plot AND you have an Mfile that records how you did it. Now you can do things like

Happy plotting trails! By the way, my Mfile is here if you would like to use it.

[Back to main page] [Back to plot page]
Comments? Contact Jim Maneval at maneval@bucknell.edu