gabboshow
gabboshow

Reputation: 5559

Double ticklabel in Matlab

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)

enter image description here

Now I would like to write:

In order to have something like the picture below:

enter image description here

How can I do this?

Upvotes: 3

Views: 726

Answers (1)

Luis Mendo
Luis Mendo

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 by str. To add text to one point, specify x and y as scalars in data units. To add text to multiple points, specify x and y 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

enter image description here

Upvotes: 2

Related Questions