1

我想从表格中创建堆积条形图。这里有一个我正在查看的表格类型的 MWE:

clear all; 

country1=rand(5,1); 
 country2=rand(5,1);
 country3=rand(5,1);
 country4=rand(5,1);
 country5=rand(5,1);

 date=1990:1994;
 T=table(date',country1,country2,country3,country4,country5);
 T.Properties.VariableNames{1}='date';
 T.Total=sum(T{:,2:end},2); 
 T{:,2:end} = T{:,2:end}./T.Total; 
 A = table2array(T);
 A(:,[1,end])=[];
 A=sort(A,2); 
 TT=array2table(A,'VariableNames',{'country1','country2','country3','country4','country5'});
TT.Date=T.date;
TT.Total=T.Total;
T_new=table(TT.Date, TT.country1,TT.country2,TT.country3,TT.country4,TT.country5,TT.Total);
T_new.Properties.VariableNames=T.Properties.VariableNames;
T_new.World=sum(T{:,2:4},2);
T_new.World=1-(T_new.country4+T_new.country5); 
T_new(:,[2:4,end-1])=[];

T_new

date    country4    country5     World 
    ____    ________    ________    _______

    1990     0.2933     0.29471     0.41199
    1991    0.31453     0.34511     0.34035
    1992    0.22595     0.29099     0.48307
    1993    0.26357     0.33336     0.40306
    1994    0.28401     0.28922     0.42677

堆叠 BAR 的类型

=====================

根据T_new表格,我想创建一个堆积条形图。在“x”轴上,图表应显示日期(1990、1991 等),每个日期应为一个堆叠条形图。因此,例如,1990应该有一个条形图堆叠值0.2933 0.29471 0.41199

理想情况下,在堆栈栏中,我还希望包含 (country1, country2, world) 的标签以表示对应的值。

我如何在 matlab 中做到这一点?

4

2 回答 2

1

您可以执行以下操作:

bar(T_new{:,1},T_new{:,2:end},'stacked')
legend(T_new.Properties.VariableNames(2:end))

堆叠条

于 2017-02-11T20:56:29.250 回答
0

您提供的代码在以下行包含错误:

T{:,2:end} = T{:,2:end}./T.Total

Error using  ./ 
Matrix dimensions must agree.
Error in stacked_bars (line 14)
T{:,2:end} = T{:,2:end}./T.Total;

因为T{:,2:end}(5 x 6)矩阵并且T.Total(5 x 1)数组

您可以修复它替换该行,例如:

T{:,2:end}=bsxfun(@rdivide,T{:,2:end},T.Total)

修复错误后,绘制标签的另一种方法(相对于已发布的答案)可能是使用text 函数在每个stackedbars.

您可以通过以下方式识别绘制字符串的点的坐标xy

  • x:对于每组条,是对应的date(您需要将该值向左移动一点,以便使文本相对于条居中,因为text使用x坐标作为起点
  • y:对于第一个标签(较低的)可能只是条形高度的一半;从第二个栏开始,您需要添加前一个栏的高度

这种方法的可能实现如下:

% Get the T_new data
x=table2array(T_new)
x=x(:,2:end)
% Ientify the number of bars
n_s_bars=size(x,2)
% Open a Figure for the plot
figure(123)
% Plot the stacked bars
bar(T_new{:,1},T_new{:,2:end},'stacked')
% Get the names of the table variables
v_names=T_new.Properties.VariableNames

% Loop over the dates
for i=1:length(date)
   % Create the label string:
   %   country_x (or world)
   %   percentage
   str=sprintf('%s\n%f',v_names{2},x(i,1))
   % Print the label in the center of the first bar
   tx=text(date(i)-.3,x(i,1)/2,str,'Color',[1 1 1])
   % Loop over the bars, starting from the second bar
   for j=2:n_s_bars
      % Create the label string:
      %   country_x (or world)
      %   percentage
      str=sprintf('%s\n%f',v_names{j+1},x(i,j))
      % Print the label in the center of the first bar
      tx=text(date(i)-.3,sum(x(i,1:j-1))+x(i,j)/2,str)
   end
end

在循环中,生成以下图像:

在此处输入图像描述

希望这可以帮助,

卡普拉

于 2017-02-12T15:01:04.210 回答