我创建了以下图像:
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)
现在我想写:
- 在第一个
0 1 2
“第 1 组”下 - 在第二个
0 1 2
“第 2 组”下 - 在第三个
0 1 2
“第 3 组”下
为了得到像下图这样的东西:
我该怎么做?
最佳答案
您可以使用 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.
您可能希望使用 text
对象的 'Extent'
属性在每个组中将它们水平居中。此外,您可能需要稍微垂直压缩轴,以便为下面的文本腾出空间。
%// 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
关于matlab - Matlab 中的双刻度标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33165830/