✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.

# Treemaps in MATLAB®

How to make a Treemap plot in MATLAB® using Treemaps and Plotly. Treemaps are used to visualize hierarchical data as nested rectangels.

### Treemap with Defined Labels and Colors

%% Download Treemap here:
%% http://www.mathworks.com/matlabcentral/fileexchange/17192-treemap

n = 15;
data = rand(1,n);

colors = (jet(n)+1)/2;

labels = {};
for i = 1:n
labels{i} = sprintf('%2.1f%%',100*data(i)/sum(data));
end

fig=figure;

cla
rectangles = treemap(data);
plotRectangles(rectangles,labels,colors);

fig2plotly(fig);


### Treemap with Sample Data

%% Download Treemap here:
%% http://www.mathworks.com/matlabcentral/fileexchange/17192-treemap

data = ...
'Texas'	261797;
'California',155959;
'Montana',145552;
'New Mexico',121356;
'Arizona',113635;
'Oregon',95997};

colors = ones(10,3);
rectangles = treemap([data{:,2}]);
labels = data(:,1);

fig=figure;

cla
plotRectangles(rectangles,labels,colors)
outline(rectangles)
axis([-0.01 1.01 -0.01 1.01])
title('The Ten Biggest U.S. States')

fig2plotly(fig)


### Nested Treemaps

%% Download Treemap here:
%% http://www.mathworks.com/matlabcentral/fileexchange/17192-treemap

m = 12;
n = 20;
data = rand(m,n);

level1 = sum(data);

fig=figure;

cla reset
r = treemap(level1);

for j = 1:n
colors = (3*repmat(rand(1,3),m,1) + rand(m,3))/4;
rNew = treemap(data(:,j),r(3,j),r(4,j));
rNew(1,:) = rNew(1,:) + r(1,j);
rNew(2,:) = rNew(2,:) + r(2,j);
plotRectangles(rNew,[],colors)
end

outline(r)
axis([-0.01 1.01 -0.01 1.01])

fig2plotly(fig)