I can't figure out how to create the legends (for colors) in the attached code?
test1=[5 10 7;
1 100 0;
1 3 2];
test2=[10 15 10;
10 80 10;
5 5 15];
test3=[10 10 10;
20 200 20;
30 10 30];
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
First, I would rename all core
s to core1
, core2
and core3
to correspond to test1
, test2
and test3
, and also not to override the handles. Then, if you check the size of each of these using eg size(core1)
, you will see that each of these contains 3 handles to 3 plots. All 3 have the same color, so you can just pick one handle and supply it to the legend
as a first argument. So at the end you just need to add
legend([core1(1) core2(1) core3(1)], {'A', 'B', 'C'});
The full code
test1=[5 10 7;
1 100 0;
1 3 2];
test2=[10 15 10;
10 80 10;
5 5 15];
test3=[10 10 10;
20 200 20;
30 10 30];
core1=bar3(test1);
set(core1,'FaceColor',[1 0 0]); %red
for i=1:length(core1)
zz=get(core1(i),'Zdata');
k=1;
for j= 0:6:(6*length(core1)-6)
zz(j+1:j+6,:)=zz(j+1:j+6,:)+test2(k,i);
k=k+1;
end
set(core1(i),'Zdata',zz);
end
legend({'A'});
hold on
core2=bar3(test2);
set(core2,'FaceColor',[0 1 1]);%cyan
hold off
for i=1:length(core2)
zz=get(core2(i),'Zdata');
k=1;
for j= 0:6:(6*length(core2)-6)
zz(j+1:j+6,:)=zz(j+1:j+6,:)+test3(k,i);
k=k+1;
end
set(core2(i),'Zdata',zz);
end
hold on
core3=bar3(test3);
set(core3,'FaceColor',[1 1 0]);%yellow
hold off
legend([core1(1) core2(1) core3(1)], {'A', 'B', 'C'});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.