且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Matlab:3D堆积条形图

更新时间:2023-11-21 23:03:10

在第一个循环中使用:
$ (j + 1:j + 6,...)= zz(j + 1:j + 6,...)+ test2(k,i)+ test3( K,I);

而不是 zz(j + 1:j + 6,:)= zz(j + 1:j + 6,:)+ test2(k,i);



或者你可以使用相同的字符串在第二个循环中。


I'm trying to create a 3D stacked bar chart as in this question: 3D stacked bars in Matlab. However unlike that question I want to use 3 datasets instead of 2. I think I have a (probably simple) problem where the bars don't shift up correctly or something similar.

The three datasets I have are called test1, test2 and test3 and are respectively:

5 10 7
1 100 0
1 3 2

10 15 10
10 80 10
5 5 15

10 10 10
20 200 20
30 10 30

And plotting them produces this:

As you can see the central bar should add up to 380 but is only 280 tall. The bars for one of the datasets seem to be rendered "inside" the other two datasets, which would also explain why the bars have 3 central separation lines instead of the 2 we'd expect.

The code I'm using is:

core=bar3(test1);
set(core,'FaceColor',[1 0 0]); %red

for i=1:length(core)
    zz=get(core(i),'Zdata');
        k=1;
        for j= 0:6:(6*length(core)-6)
            zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);
            k=k+1;
        end
    set(core(i),'Zdata',zz);
end

hold on

core=bar3(test2);

set(core,'FaceColor',[0 1 1]);%cyan
hold off

for i=1:length(core)
    zz=get(core(i),'Zdata');
    k=1;
    for j= 0:6:(6*length(core)-6)
        zz(j+1:j+6,:)=zz(j+1:j+6,:)+test3(k,i);
        k=k+1;
    end
    set(core(i),'Zdata',zz);
end


hold on
core=bar3(test3);
set(core,'FaceColor',[1 1 0]);%yellow
hold off

How do I make the bars shift up properly? Or alternatively, how can I use Matlab code to make a 3D stacked bar chart for the data? Any help greatly appreciated, thanks for your time.

In the first loops use:

 zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i)+test3(k,i);

instead of zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);.

Or you can use the same string in the second loops.