在matlab中向分组条形图添加数据标签
我想在matlab中将数据添加到分组条形图中。但是,我不能将每个数据放在每个栏的顶部。对于常用的条形图和,我尝试了下面的分组图代码,但xpos和ypos是不正确的。感谢您的帮助在matlab中向分组条形图添加数据标签,matlab,bar-chart,Matlab,Bar Chart,我想在matlab中将数据添加到分组条形图中。但是,我不能将每个数据放在每个栏的顶部。对于常用的条形图和,我尝试了下面的分组图代码,但xpos和ypos是不正确的。感谢您的帮助 a=[0.92,0.48,0.49]; b=[0.74,0.60,0.30]; c=[0.70,0.30,0.10]; X=[a;b;c]; hbar = bar(X, 'grouped'); for i=1:length(hbar) XDATA=get(hbar(i),'XData')'
a=[0.92,0.48,0.49];
b=[0.74,0.60,0.30];
c=[0.70,0.30,0.10];
X=[a;b;c];
hbar = bar(X, 'grouped');
for i=1:length(hbar)
XDATA=get(hbar(i),'XData')';
YDATA=get(hbar(i),'YData')';
labels = cellstr(num2str(YDATA));
ygap=0.01;
for j=1:size(XDATA,2)
xpos=XDATA(i,1);
ypos=YDATA(i,1)+ygap;
t=[num2str(YDATA(1,j),3)];text(xpos,ypos,t,'Color','k','HorizontalAlignment','left','Rotation',90)
end
end
代码中有两个主要错误:
- 内部循环的定义:
是一个XDATA
数组,因此内部循环只进行一次迭代,因为(nx1)
是size(XDATA,2)
。这将使标签添加到每个组的中心栏上1
- 在innser循环中,首先将变量
设置为标签(t
;然后将同一变量用作t=[num2str(YDATA(1,j),3)];
函数的输出(text
;然后在另一次调用t=text(xpos,ypos,labels{i})
时使用该变量,但现在它包含标签句柄,而不再包含标签字符串。这将生成错误text
X
位置
您必须检索组中每个条的位置:每个条的X
位置由其XDATA
值加上相对于组中心的偏移量给出。偏移量值存储在条的XOffset
属性中(注意:这是一个值)
这是一种可能的实现方式:
% Generate some data
bar_data=rand(4,4)
% Get the max value of data (used ot det the YLIM)
mx=max(bar_data(:))
% Draw the grouped bars
hbar=bar(bar_data)
% Set the axes YLIM (increaed wrt the max data value to have room for the
% label
ylim([0 mx*1.2])
grid minor
% Get the XDATA
XDATA=get(hbar(1),'XData')';
% Define the vertical offset of the labels
ygap=mx*0.1;
% Loop over the bar's group
for i=1:length(hbar)
% Get the YDATA of the i-th bar in each group
YDATA=get(hbar(i),'YData')';
% Loop over the groups
for j=1:length(XDATA)
% Get the XPOS of the j-th bar
xpos=XDATA(j);
% Get the height of the bar and increment it with the offset
ypos=YDATA(j)+ygap;
% Define the labels
labels=[num2str(YDATA(j),3)];
% Add the labels
t = text(xpos+hbar(i).XOffset,ypos,labels,'Color','k','HorizontalAlignment','center','Rotation',90)
end
end
希望这有帮助
Qapla'您能编辑您的问题以包含一些示例数据(在
X
中)吗?这样我们就可以运行代码了?我更改了代码以添加一些数据@Justin先生。谢谢