Adding Legend to Bar Graph
이전 댓글 표시
I have a bar graph with a mix of colors and would like to create a legend but I can't figure out where to put it within my code.
The code I'm using is as follows:
b = bar(StepsS2.Time, StepsS2.Steps);
b.FaceColor = 'flat';
for i = 1:length(StepsS2.Time)
switch StepsS2.Action(i)
case "Jump"
b.CData(i,:) = [1 0 0];
case "Run"
b.CData(i,:) = [1 1 0];
case "Squat"
b.CData(i,:) = [0 1 1];
case "Cycle"
b.CData(i,:) = [0 0 1];
otherwise
b.CData(i,:) = [0 1 0];
end
end
I've tried a variety of solutions such as:
set(b, {'DisplayName'}, {'Jump', 'Run', 'Squat', 'Cycle', 'Other'}'), which gives the following error: Error using matlab.graphics.chart.primitive.Bar/set
Value cell array handle dimension must match handle vector length.
and also
legend(b, 'Jump', 'Run', 'Squat', Cycle', 'Other'), which only displays 'Jump'
답변 (3개)
Sulaymon Eshkabilov
2021년 7월 7일
Hi, here is an easy solution to your exercise:
Labelit={};
LEG = {"Jump", 'Run', 'Squat', 'Cycle', 'Other'};
for ii=1:5
b= bar(A(ii), B(ii)); hold on
b.FaceColor = 'flat';
Labelit{ii}=LEG{ii};
legend(Labelit{:});
end
댓글 수: 3
Gillian Murray
2021년 7월 7일
Sulaymon Eshkabilov
2021년 7월 7일
A=StepsS2.Time; B=StepsS2.Steps
Or
...
b= bar(StepsS2.Time(ii), StepsS2.Steps(ii)); hold on
...
Gillian Murray
2021년 7월 7일
Sulaymon Eshkabilov
2021년 7월 8일
If you are concerned of coloring all bars specifically, then you need to use this code:
figure()
Labelit = {};
CL = [1 0 0; 0 1 1; 0 1 0; 0 0 1; 1 0 1];
LEG = {'Jump', 'Run', 'Squat', 'Cycle', 'Other'};
for ii = 1:5
b = bar(StepsS2.Time(ii), StepsS2.Steps(ii)); hold on
b.FaceColor = 'flat';
b.CData = CL(ii,:);
Labelit{ii} = LEG{ii};
legend(Labelit{:});
end
Sulaymon Eshkabilov
2021년 7월 8일
Why you keep using this useless (removed) part of your code:
for i = 1:length(StepsS2.Time)
switch StepsS2.ActivityType(i)
case "Jump"
b.CData(i,:) = [1 0 0];
case "Run"
b.CData(i,:) = [0 1 1];
case "Squat"
b.CData(i,:) = [0 1 0];
case "Cycle"
b.CData(i,:) = [0 0 1];
otherwise
b.CData(i,:) = [1 0 1];
end
end
This is the complete code:
figure()
Labelit = {};
CL = [1 0 0; 0 1 1; 0 1 0; 0 0 1; 1 0 1];
LEG = {'Jump', 'Run', 'Squat', 'Cycle', 'Other'};
for ii = 1:5
b = bar(StepsS2.Time(ii), StepsS2.Steps(ii)); hold on
b.FaceColor = 'flat';
b.CData = CL(ii,:);
Labelit{ii} = LEG{ii};
legend(Labelit{:});
end
카테고리
도움말 센터 및 File Exchange에서 Discrete Data Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

