Adding Legend to Bar Graph
26 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
Sulaymon Eshkabilov
am 7 Jul. 2021
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 Kommentare
Sulaymon Eshkabilov
am 7 Jul. 2021
A=StepsS2.Time; B=StepsS2.Steps
Or
...
b= bar(StepsS2.Time(ii), StepsS2.Steps(ii)); hold on
...
Sulaymon Eshkabilov
am 8 Jul. 2021
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
1 Kommentar
Sulaymon Eshkabilov
am 8 Jul. 2021
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
Siehe auch
Kategorien
Mehr zu Discrete Data Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

