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

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.

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.

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.

or

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

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.

Neuroscientist and data scientist at Columbia University. On Twitter: @NeuroJoJo