Using a for loop to graph values using different colors
6 views (last 30 days)
Show older comments
I'm using some distances and I want to plot them. On my plot they should have a different color depending on how far away the are. Right now when I run my code, they're all being displayed with the same color. How can I make my distances different colors depending on their distance?
clear all
close all
data = [3 24 30 26 22 14 15 7 5 9];
t = (1:length(data));
for i = 1:length(data);
if data(data <= 30 & data > 20)
scatter(t,data,'.g');
hold on;
elseif data(data <= 20 & data > 10)
scatter(t,data,'.y');
hold on;
elseif data(data <= 10 & data >= 0)
scatter(t,data,'.r');
hold on;
end
xlabel('time (seconds)')
xlim([0 13])
ylabel('distance(meters)')
ylim([0 35])
title('Distance of Vehicle Over Time')
end
0 Comments
Accepted Answer
Ameer Hamza
on 13 Apr 2020
Edited: Ameer Hamza
on 13 Apr 2020
There were issues with the if conditions. Check the corrected code. Also, note that you were plotting to scatter plot with all points.
clear all
close all
data = [3 24 30 26 22 14 15 7 5 9];
t = (1:length(data));
for i = 1:length(data)
if data(data(i) <= 30 & data(i) > 20)
scatter(t(i),data(i),'+b', 'Linewidth', 2);
hold on;
elseif data(data(i) <= 20 & data(i) > 10)
scatter(t(i),data(i),'+m', 'Linewidth', 2);
hold on;
elseif data(data(i) <= 10 & data(i) >= 0)
scatter(t(i),data(i),'+r', 'Linewidth', 2);
hold on;
end
xlabel('time (seconds)')
xlim([0 13])
ylabel('distance(meters)')
ylim([0 35])
title('Distance of Vehicle Over Time')
end
0 Comments
More Answers (1)
Turlough Hughes
on 13 Apr 2020
Edited: Turlough Hughes
on 13 Apr 2020
If you want to use scatter so that the color depends on distance, this is how you do it:
% Data
clear all
close all
data = [3 24 30 26 22 14 15 7 5 9];
t = (1:length(data));
scatter(t,data,[],data,'filled') % < modified code
xlabel('time (seconds)')
xlim([0 13])
ylabel('distance(meters)')
ylim([0 35])
title('Distance of Vehicle Over Time')
If you specifically require 3 colors, you have the option of setting the colormap with just three sets of color triplets as follows:
colormap([1 0 0; 0 1 0; 0 0 1])
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!