Color-Coded Bar Graph
显示 更早的评论
I have a table with 3 columns, Time, Steps, Action and am trying to make a bar graph. I want time on the x-axis and steps on the y-axis and I want to color code based on action. I am using the following code, but my graph is coming out just one color, blue which maybe because the first data point is cycle. I'm not sure what I'm doing wrong. Thanks in advance for your help!
figure(1)
hold on
for i = 1:length(StepsS2.Time)
b = bar(StepsS2.Time, StepsS2.Steps);
if StepsS2.Action(i) == 'Jump'
set(b, 'FaceColor', 'r');
elseif StepsS2.Action(i) == 'Run'
set(b, 'FaceColor', 'y');
elseif StepsS2.Action(i) == 'Squat'
set(b, 'FaceColor', 'c');
elseif StepsS2.Action(i) == 'Cycle'
set(b, 'FaceColor', 'b');
else
set(b, 'FaceColor', 'g');
end
end
hold off
1 个评论
dpb
2021-7-6
Your code above is drawing the same bar graph over and over on top of the previous rendition for each pass through the loop.
With only a vector for the y variable, bar() creates only a single bar object and all bars are the same color. It is blue in the end because the last datapoint must be 'Cycle', not the first.
You need to rearrange the data in the table to have a variable for each bar wanted; fill the missing values for the times with NaN so those values will be ignored.
Then call bar() just once and set the colors using the array of bar handles.
I demonstrated for a smaller case just recently at https://www.mathworks.com/matlabcentral/answers/871108-legend-in-bar-plot?s_tid=srchtitle although there used a 'Stacked' plot to be able to get the three bars since bar() treats a vector y as one bar object regardless of the input orientation. You've got an array so won't run into that limitation.
Attach a .mat file if want somebody to play directly with your data...
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!