Use MATLAB to create beautiful, custom violin plots

One of the most desired plot types, a favorite of R users, is the violin or half-violin. In this post I show how to accomplish this in MATLAB using two built-in functions: ksdensity and patch.

Jozsef Meszaros
2 min readFeb 3, 2022
After reading this post, you will be able to understand the magic behind these graphs and make one yourself!

Has this ever happened to you?

You have some great data for a boxplot, but you also want to view the distributions. Your supervisor suggests something called a violin, but you’re a MATLAB native and the last time you saw a violin was in your high school orchestra section. So you go looking:

There are some homemade solutions on the MathWorks page, but in general they don’t have the same aesthetic as what you’d see from an R package.

Here I will guide you through making a very basic half-violin, and a more complex example follows

Step 1: Create some fake data. We’ll create data that is a combination of two Gaussian distributions, with means at 0 and 10, and standard deviations of 5 and 1.

rng(5)mu = [0,10];
sigma = [5,0;0,1];
gm = gmdistribution( mu,sigma );
data = random(gm,30);
data = data(:);

Step 2: Create a kernel density function from your data, which is at the heart of those lovely half-violins.

xvalues = linspace( prctile(data,1), prctile(data,99), 100 );[f,xi] = ksdensity( data(:),xvalues,'Bandwidth',1,'BoundaryCorrection','reflection');

Step 3: Use patch for displaying it, and viola (or should we say, violin!)

figure; patch( 0-[f,zeros(1,numel(xi),1),0],[xi,fliplr(xi),xi(1)],'r' )

Tip: If your graph looks like it’s filling up the whole plot box, try adjusting the value of ‘Bandwidth’ in the ksdensity command.

By resizing the window, you can actually configure how the plot looks (which is one of the biggest advantages of plotting with MATLAB over R or Jupyter, in my opinion).

Now you understand the basics of plotting the violin using ksdensity and patch. In the gist below, I lay out how to generate the graph in the top panel. If you want to fully understand all the code I recommend you check out my other posts about how to grab objects in a figure, as well as arrayfun and patch.