Matlab Tip of the Day: Changing line properties programmatically

I have an undergraduate working with me on some simulations, and I've been teaching him Matlab for the last year. This week I showed him a useful trick for changing the look of some line plots. He has a whole bunch of these to do, and instead of replotting the data or using the Plot Tools GUI to edit each figure, I taught him how you can get at the various properties of the plot. Once he figured out which properties he wanted to change, and which way, he could save the commands as a script, and run it on any open image to get a consistent look.1

lineHandles = get(gca, 'children');

lineHandles is a list of numbers, one for each line in your plot.2 These numbers are the "handles" of the plotted curves. In my undergrad's case, there are four curves, so lineHandles returns a list of four values.

If you want to know what the properties are called, or what they're currently set to, you can run lineProps = get(lineHandles) for a list.

For the plots we were changing, we wanted four blue curves to become a red, a green, a blue and a black curve, and we wanted to make the line thicker. The properties we needed were 'Color' and 'LineWidth'.

image.jpg

 

 

set(lineHandles(1), 'Color', 'k', 'LineWidth', 3)
set(lineHandles(2), 'Color', 'b', 'LineWidth', 3)
set(lineHandles(3), 'Color', 'g', 'LineWidth', 3)
set(lineHandles(4), 'Color', 'r', 'LineWidth', 3)

We reversed the order of the colors vs. the order in lineHandles to match the pattern we wanted. I believe the ordering in lineHandles is based on the order the curves were added to the plot, but I don't know that for sure.

image.jpg

Now that our lines are thicker, the axes look wimpy, so we can beef them up, too:

set(gca, 'LineWidth', 2)
image.jpg

1: This assumes the plot to change is open and is the "current" axes. If you just opened the figure and it has only one set of axes, then it should run just fine. If there are multiple axes in the current figure, you can use

axisHandles = get(gcf, 'children');
lineHandles = get(axisHandles(x), 'children');

axisHandles would then have as many entries as there are axes in the figure. To get the particular set of axes you want, you'll need to pick the right integer for x.

2: I'm only addressing line plots here. The properties for bar charts are a little different.