Custom legend with RGB Triplet bar graph

2 次查看(过去 30 天)
I tried to customize my bar graph and my legend with RGB Triplet.
AS you can see the legend doesn't match with my color choice. It should be in purple in the legend.
I tried this solution, but it doesn't work
bh(2) = bar(nan,nan,0.4940 0.1840 0.5560);
What should i Do to have a match ?
figure (5)
%modifié
X=categorical({'small','medium','large'});
X=reordercats(X,{'small','medium','large'});
Y=[5 18 56];
TestL={'Mon','Tue','Wed'};
figure()
b=bar(X,Y);
hold on
b.FaceColor = 'flat';
b.CData(1,:)=[1 0 0];
%b.CData(2,:)=[0 1 0];
b.CData(2,:)=[0.4940 0.1840 0.5560];
b.CData(3,:)=[0 0 1];
bh(1) = bar(nan,nan,'r');
bh(2) = bar(nan,nan);%
bh(3) = bar(nan,nan,'b');
bh(2).CData=[0.4940 0.1840 0.5560];
legend(bh, TestL, 'location', 'best') %'northwest'
%legent at the top
xtips1 = b(1).XEndPoints;
ytips1 = b(1).YEndPoints;
labels1 = string(b(1).YData);
text(xtips1,ytips1,labels1,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
ylabel('Energie [kWh]')

采纳的回答

Mann Baidi
Mann Baidi 2023-10-5
编辑:Mann Baidi 2023-10-5
Hi Jonathan,
I understand that you would like to customize the color appearing in the legend. You can try changing the color by changing the "bh(2).FaceColor". You can try the following code:
%modifié
X=categorical({'small','medium','large'});
X=reordercats(X,{'small','medium','large'});
Y=[5 18 56];
TestL={'Mon','Tue','Wed'};
figure()
b=bar(X,Y);
hold on
b.FaceColor = 'flat';
b.CData(1,:)=[1 0 0];
%b.CData(2,:)=[0 1 0];
b.CData(2,:)=[0.4940 0.1840 0.5560];
b.CData(3,:)=[0 0 1];
bh(1) = bar(nan,nan,'r');
bh(2) = bar([nan,nan]);%
bh(3) = bar(nan,nan,'b');
bh(2).FaceColor=[0.4940 0.1840 0.5560];
legend(bh, TestL, 'location', 'best') %'northwest'
%legent at the top
xtips1 = b(1).XEndPoints;
ytips1 = b(1).YEndPoints;
labels1 = string(b(1).YData);
text(xtips1,ytips1,labels1,'HorizontalAlignment','center',...
'VerticalAlignment','bottom')
ylabel('Energie [kWh]')
Hope this resolves your issue!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by