Konstantin Schubert
Konstantin Schubert

Reputation: 3356

Adding points with error bars into a Matlab scatter plot

I have performed a multidimensional cluster analysis in matlab. For each cluster, I have calculated mean and covariance (assuming conditional independence).

I have chosen two or three dimensions out of my raw data and plotted it into a scatter or scatter3 plot. Now I would like to add the cluster-means and the corresponding standart deviations into the same plot.

In other words, I wand to add some data points with error bars to a scatter plot.

This question is almost what I want. But I would be ok with bars instead of boxes and I wonder if in that case there is a built-in way to do it with less effort.

Any suggestions on how to do that?

Upvotes: 3

Views: 9528

Answers (2)

bbarker
bbarker

Reputation: 13078

Once you realize that line segments will probably suffice for your purpose (and may be less ugly than the usual error bars with the whiskers, depending on the number of points), you can do something pretty simple (which applies to probably any plotting package, not just MATLAB).

Just plot a scatter, then write a loop to plot all line-segments you want corresponding to error bars (or do it in the opposite order like I did with error bars first then the scatter plot, depending if you want your dots or your error bars on top).

Here is the simple MATLAB code, along with an example figure showing error bars in two dimensions (sorry for the boring near-linearity):

enter image description here

As you can see, you can plot error bars for each axis in different colors to aid in visualization.

function scatterError(x, y, xe, ye, varargin)
%Brandon Barker 01/20/2014

nD = length(x);

%Make these defaults later:
dotColor = [1 0.3 0.3]; % conservative pink
yeColor = [0, 0.4, 0.8]; % bright navy blue
xeColor = [0.35, 0.35, 0.35]; % not-too-dark grey
dotSize = 23;

figure();
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
set(gca, 'FontSize', 23);
hold all;

for i = 1:nD
    plot([(x(i) - xe(i)) (x(i) + xe(i))], [y(i) y(i)], 'Color', xeColor);
    plot([x(i) x(i)], [(y(i) - ye(i)) (y(i) + ye(i))], 'Color', yeColor);
end

scatter(x, y, dotSize, repmat(dotColor, nD, 1));
set(gca, varargin{:});
axis square;

With some extra work, it wouldn't be too hard to add whiskers to your error bars if you really want them.

Upvotes: 2

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

If you are not too picky about what the graph looks like and are looking for performance, a builtin function is indeed often a good choice.

My first thought would be to try using a boxplot, it has quite a lot of options so probably one combination of them will give you the result you need.

Sidenote: At first sight the answer you referred to does not look very inefficient so you may have to manage your expectations when it comes to achievable speedups.

Upvotes: 0

Related Questions