Using a for loop to graph values using different colors
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Ameer Hamza
2020-4-13
编辑:Ameer Hamza
2020-4-13
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 个评论
更多回答(1 个)
Turlough Hughes
2020-4-13
编辑:Turlough Hughes
2020-4-13
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])
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!