Adding Legend to Bar Graph
26 ビュー (過去 30 日間)
古いコメントを表示
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'
0 件のコメント
回答 (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 件のコメント
Sulaymon Eshkabilov
2021 年 7 月 7 日
A=StepsS2.Time; B=StepsS2.Steps
Or
...
b= bar(StepsS2.Time(ii), StepsS2.Steps(ii)); hold on
...
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
参考
カテゴリ
Help Center および File Exchange で Discrete Data Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

