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!