Thursday, December 18, 2008

Pretty Plots in MATLAB

Using MATLAB to crank through some calculations, but having trouble making the plots pretty? Here's an example that should make a nice looking plot that's ready to be inserted into a report.

figure
set(gca,'fontsize',14)
set(gcf, 'PaperSize', [8. 6.],'PaperPositionMode', 'auto');
plot(X,Y,'k^','markersize',10,'markerfacecolor','auto')
legend('mylegend','location','northeast');
xlabel('myxlabel','Interpreter','latex','fontsize',16);
ylabel('myylabel','Interpreter','latex','fontsize',16)
AXIS([xmin xmax ymin ymax])
print('-r600','-dpdf',['filename','.pdf'])

Alright, a quick rundown.

1. The 'figure' command is letting MATLAB know that we're making a picture with all the following attributes.
2. The 'set gca' command is setting the axes, which have the default handle 'gca', to have a font size of 14 here. This will control the size of the numbering on the axes, as well as the size of the font in the legend.
3. The 'set gcf' command is setting the paper size to 8" by 6", a size I find works well with the default figure output of MATLAB. This will prevent you from having to crop the plot later in a third-party photo editor.
4. The 'plot' command lists the X and Y arrays youd like to plot, 'k^' plots black upward facing triangles in a 'marker size' of 10pt, and automatically filled.
The 'legend' command puts in your legend, one entry per pair of vectors being plotted, in the northwest position.
5. The 'xlabel' and 'ylabel' commands are pretty straightforward, but the interpretter command displays the labels in the default LaTeX font instead of the MATLAB font. You can use the '$$' pairing to put in maths.
6. The 'axis' command sets the range for x and y, just comment this out if you like what MATLAB does.
7. The 'print' command will save your figure as .pdf with the filename you specify in the current directory (where your .m file is). Here, you can always specficy a path if you'd like to save figures in a different folder.

Still to come, using str2num and num2str to automatically number plots that are part of a for loop, or to name output graphs based on input data.

No comments:

Post a Comment

Sociable