Reputation: 5559
I create the following image:
figure
y = [2 2 3 2 5 6 2 8 9];
bar(y)
name_x = {'0','1','2','0','1','2','0','1','2'}
set(gca,'Xtick',1:9,'XTickLabel',name_x,'XTickLabelRotation',45)
Now I would like to write:
0 1 2
"Group 1"0 1 2
"Group 2"0 1 2
"Group 3" In order to have something like the picture below:
How can I do this?
Upvotes: 3
Views: 726
Reputation: 112659
You can add group names using text
:
text(x,y,str)
adds a text description to one or more data points in the current axes using the text specified bystr
. To add text to one point, specifyx
andy
as scalars in data units. To add text to multiple points, specifyx
andy
as vectors with equal length.
You may want to use the 'Extent'
property of text
objects to center them horizontally in each group. Also, you may need to vertically compress the axis a little to make room for the texts below.
%// Original graph
figure
y = [2 2 3 2 5 6 2 8 9];
bar(y)
name_x = {'0','1','2','0','1','2','0','1','2'};
set(gca,'Xtick',1:9,'XTickLabel',name_x,'XTickLabelRotation',45)
%// Add groups
groupX = [2 5 8]; %// central value of each group
groupY = -1; %// vertical position of texts. Adjust as needed
deltaY = .03; %// controls vertical compression of axis. Adjust as needed
groupNames = {'Gr. 1', 'Group 2', 'Grrroup 3'}; %// note different lengths to test centering
for g = 1:numel(groupX)
h = text(groupX(g), groupY, groupNames{g}, 'Fontsize', 13, 'Fontweight', 'bold');
%// create text for group with appropriate font size and weight
pos = get(h, 'Position');
ext = get(h, 'Extent');
pos(1) = pos(1) - ext(3)/2; %// horizontally correct position to make it centered
set(h, 'Position', pos); %// set corrected position for text
end
pos = get(gca, 'position');
pos(2) = pos(2) + deltaY; %// vertically compress axis to make room for texts
set(gca, 'Position', pos); %/ set corrected position for axis
Upvotes: 2