Quantcast
Channel: Undocumented Matlab
Viewing all articles
Browse latest Browse all 219

Bar plot customizations

$
0
0

Bar charts are a great way to visualize data. Matlab includes the bar function that enables displaying 2D bars in several different manners, stacked or grouped (there’s also bar3 for 3D bar-charts, and barh, bar3h for the corresponding horizontal bar charts).

Displaying stacked 1D data

bar is basically a high-level m-file wrapper for the low-level specgraph.barseries object. Such wrappers are generally a good thing, assigning default property values, checking the input data for illegal values etc. But in some cases, they are simply too smart. One such case happened to me a few days ago, when I needed to display a stacked chart of some data values. This works great when the data is a 2D matrix, but when the data happens to be 1D (a single row), bar decides to display the values in separate bars (left screenshot), rather than in a single stacked bar (right screenshot), even when I specifically ask for a ‘stacked’ graph:

bar([6,4,1], 'Stacked');

Default bar plot of 1D data

Default bar plot of 1D data

  
Bar plot of 1D data - stacked

Bar plot of 1D data - stacked


I could of course revert to the lower-level specgraph.barseries. But in this case the simple workaround was to add a dummy data row of Nan values, tricking bar into thinking it’s a 2D data. Since Nan values are never plotted in Matlab, we get the requested stacked bar, alongside an empty bar next to it. All we need to do now is to delete the extra tick-label for the dummy (empty) bar and we’re done:

bar([6,4,1; nan(1,3)], 'Stacked');
set(gca,'xtick',1)

or, more generally (taking care of both 2D and 1D data):

bar([data; nan(size(data))],'Stacked');
set(gca, 'xtick',1:size(data,1));

Displaying data labels

One of the features that I miss most in Matlab bar-charts is the ability to easily add data labels next to the colored patches. This can be added programmatically as I’ll just show, but it would be much better if there were properties that controlled this. Here’s my implementation:

First, let’s display a simple stacked bar chart:

data = [6,4,1; 5,2,2; 4,0,0; 2,0,1; 0,2,0; 0,1,1];
hDataSeries = bar(data,'stacked');
set(gca, 'xlim',[0,7], 'box','off');

Default bar plot of 2D data

Default bar plot of 2D data

Now let’s add the bar totals on top of the bars:

sumTotals = sum(data,2);
sumTotals = sumTotals(~isnan(sumTotals));
labels = arrayfun(@num2str,sumTotals,'uniform',false);
hText = text(1:size(data,1), sumTotals, labels);
set(hText, 'VerticalAlignment','bottom', 'FontSize',8, 'Color','b');

Bar plot with totals

Bar plot with totals

Now let’s add the individual data-series labels, but only next to bars that have 2 or more components:

hPatches = get(hDataSeries,'Children');
try hPatches = cell2mat(hPatches); catch, end  % no need in case of single patch
xData = get(hPatches(1),'XData');
xPos = xData(end,:) + 0.01;
yData = get(hPatches,'YData');
try yData = cell2mat(yData); catch, end
barYs = yData(2:4:end,:);
barValues = diff([zeros(1,size(barYs,2)); barYs]);
barValues(bsxfun(@minus,barValues,sum(barValues))==0) = 0;  % no sub-total for bars having only a single sub-total
yPos = yData(1:4:end,:) + barValues/2;
xPos = xPos(ones(1,size(yPos,1)),:);
xPos(barValues==0)      = [];  % remove entries for empty bars patches
yPos(barValues==0)      = [];  % remove entries for empty bars patches
barValues(barValues==0) = [];  % remove entries for empty bars patches
labels = strcat(' ', arrayfun(@num2str,barValues(:),'uniform',false));
hText = text(xPos(:), yPos(:), labels);
set(hText, 'FontSize',8);

Finally, add the legend and we’re done:

hLegend = legend(hDataSeries, {'Blue','Green','Red'});
set(hLegend, 'FontSize',8);

Bar plot with totals & legend

Bar plot with sub-totals & legend

Additional customization of the bar patches can be made using the patch handles, which are included as children of the returned hDataSeries handles:

hDataSeries = bar(...);
hPatches = get(hDataSeries, 'Children');
try hPatches = cell2mat(hPatches); catch, end  % no need in case of single patch

Note: hDataSeries is an array of handles, one per data column. Each handle is an hggroup of patches. As with all patches, we can customize their face and edge line-style, width, color, transparency, shading/lighting etc.

 
Related posts:
  1. Undocumented scatter plot behavior The scatter plot function has an undocumented behavior when plotting more than 100 points: it returns a single unified patch object handle, rather than a patch handle for each specific...
  2. Undocumented scatter plot jitter Matlab's scatter plot can automatically jitter data to enable better visualization of distribution density. ...
  3. Bug and workaround in timeseries plot Matlab's internal hgconvertunits function has a bug that affects timeseries plots. Luckily there is a simple workaround....
  4. Plot LimInclude properties The plot objects' XLimInclude, YLimInclude, ZLimInclude, ALimInclude and CLimInclude properties are an important feature, that has both functional and performance implications....
 

Viewing all articles
Browse latest Browse all 219

Trending Articles