matlab - Matlab 中的双刻度标签

标签 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

我该怎么做?

最佳答案

您可以使用 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.

您可能希望使用 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

enter image description here

关于matlab - Matlab 中的双刻度标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33165830/

相关文章:

用于信号处理的 C++ 库

python - 如何在 python 中的同一个图形上绘制多个密度图

matlab - 在 matlab 中有效地扰乱 nx1 矩阵?

matlab - 如何在不知道名称的情况下访问 .mat 文件中的 "Value"?

python - 如何从 DOT 文件中获取端口信息

algorithm - 最小生成树 (MST) 算法变体

r - r中的情节标题中的下标

matlab - 有没有办法绘制具有不同(交替)高度的轴值?

MATLAB 如何从原始类中的类中的方法修改值类的属性?

java - 图 edu.uci.ics.jung 中距顶点最远的 K 个点