recipes : Plotting : Distributions : Improving clarity by "jittering" data points

Problem

How do I "jitter" points on a plot?

Solution

Adding a small amount of random "jitter" to points (usually on the x axis) is a common visual trick. You can add uniformly distributed noise using the randn command.

y=0:0.01:1;
x=ones(size(y));

clf
plot(x,y,'ok') %Non-jittered data
hold on
x=x+rand(size(x))+1.5;
plot(x,y,'or') %Jittered data
hold off
xlim([0,4])

We will now jitter the black data using its plot handle. In this case I deliberately didn't store the handles for the plot objects (which I'd have done by: p=plot(x,y,'ok'), for example) in order to demonstrate a way of retrieving the handles. Furthermore, below I show how you can retrieve from the plot the data used to plot the black points.

c=get(gca,'Children'); %The second handle is that for the first plotted data
x=get(c(2),'XData'); %Retrieve the X data for the black points

%Add uniformly distributed random numbers to the data and re-plot
r=rand(size(x));
r=r-mean(r);
set(c(2),'XData',x+r)

Discussion

The first approach is useful for adding jitter to data as you plot them. The second approach allows you to add jitter to any previously plotted data. This is more flexible since you can use this technique to write a self-contained function that will add jitter to any plotted data. For an example of how jittering can help in a real plot, see this bar chart recipe.