Friday, May 22, 2015

3-D bar graph with Matlab (and why you should not use it)

Matlab has an important set of display function to perform data visualization. Among them, a few ones allow performing 3D visualization of 2D data.

I am going to talk about the bar3 and hist3 function which are the nicer ones according to me


Hist3

The data sample used for this plots are generated  using the randn function:
figure;
hist3(randn(1000,2));
This return a 2D matrix with the histogram of the two arrays (globally a random Gaussian mixture).

The hist3 function  allows to plot the data straight in a figure (if the ";" is not present) and give the following results:

Samples of plot using the hist3 function
The following attribute can be changed:
% change the transparency
alpha(0.5);
% define the color of the face according to the height (left and right)
set(get(gca,'child'),'FaceColor','interp','CDataMode','auto');
% define the color of the face according to the height (center)
set(get(gca,'child'),'FaceColor','flat','CDataMode','auto');
% change the colormap
colormap('cool');
% accelerate the display using OpenGL for the rendering
set(gcf,'renderer','opengl');


Bar3

The function bar3 offer more flexibility than hist3 and is just intended to be used for a display purpose.

In order to get the similar data as for the previous example we get the bivariate histogram of two random vectors:
dataSample = hist3(randn(1000,2));
figure;
bar3(dataSample);
This function allows to plot a similar kind of shape but offer more flexibility.
Samples of plot using the bar3 function
It is possible to access each bar of the plot one by one and to change the width, the color, the visibility and the transparency (among others) of them.

change the width:

width = 0.5;
bar3(dataSample, width);

change the color

% first subplot
for n=1:numel(h)
     cdata=get(h(n),'zdata');
     set(h(n),'cdata',cdata,'facecolor','interp')
end

% second and third subplot
for n=1:numel(h)
     cdata=get(h(n),'zdata');
     cdata=repmat(max(cdata,[],2),1,4);
     set(h(n),'cdata',cdata,'facecolor','flat')
end

change the visibility

% second subplot
for iSeries = 1:numel(h)
    zData = get(h(iSeries),'ZData');
    index = logical(kron(zData(2:6:end,2) == 0,ones(6,1)));
    zData(index,:) = nan;
    set(h(iSeries),'ZData',zData);
end

change the color

% classic method
colormap(axis3, 'summer');
cmap = colormap(axis3);
cmap = flipud(cmap);
colormap(axis3, cmap);

How and where to use it

This visualization tool should be used with care since it does not display the information accurately.

It is, however, a very good tool to explain a methodology.

No comments:

Post a Comment