Matlab中的双重ticklabel

时间:2015-10-16 08:30:18

标签: matlab graph plot label matlab-figure

我创建了以下图片:

    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

现在我想写一下:

  • 在第一个0 1 2“第1组”
  • 在第二个0 1 2“第2组”
  • 在第三个0 1 2“第3组”

为了得到如下图所示的内容:

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以使用text添加群组名称:

  

text(x,y,str)使用str指定的文本为当前轴中的一个或多个数据点添加文本说明。要将文字添加到一个点,请将xy指定为数据单位中的标量。要将文字添加到多个点,请将xy指定为长度相等的矢量。

您可能希望使用'Extent'个对象的text属性在每个组中水平居中。此外,您可能需要将轴稍微垂直压缩到腾出空间以获取下面的文本。

%// 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