Day 18: An underutilized MATLAB trick to help you patch up your plots

Jozsef Meszaros
2 min readMay 23, 2020

--

In addition to making cool pictures, the patch function can actually be used for something pretty useful. It can be used to add an additional dimension to your plot lines.

Suppose you have data where you know there are two things taking place along the x-axis. Simple example: day and night. You might put ugly lines on the figure or even worse, add arrows manually — all of which clusters up the graph. Here’s an organized and efficient way to do it using patch.

Start with some toy data. In our case, We’ll use 0’s to specify night and 1’s to specify day.

x_values = [1:15];
time_of_day = [0,0,0,0,0,1,1,1,1,1,0,0,0,0,0];
activity_level = [ normrnd(0,1,[5,1]); normrnd(10,1,[5,1]);... normrnd(0,1,[5,1]) ];

The output we’d like is if our data points were colored differently based on the value in time_of_day. Let’s give it a try with the patch function and see what we get.

patch( x_values, activity_level, time_of_day );

Uh, no. Looks cool but not sure why you’d do it. The solution doesn’t involve setting a property of patch, actually, but instead, you have to either set the last value of your y-data to nan’s or add nan’s at the end of your data.

activity_level(end) = nan;

or

x_values(end+1) = nan;
time_of_day(end+1) = nan;
activity_level(end+1) = nan;

Redo the patch function, with a couple of properties to get you the dots for the scatter plot:

patch( x_values, activity_level, time_of_day, 'Marker','o', 'MarkerFaceColor', 'flat' );

That’s it! Easy as that. Not a lot to remember, just that you always need to input the x-values, the y-values, and the color — with a nan at the end.

In case you’re a visual learner, I’ve summarized this entire post here.

--

--

Jozsef Meszaros
Jozsef Meszaros

No responses yet