Using a for loop to graph values using different colors

4 visualizaciones (últimos 30 días)
Mariana Lugo
Mariana Lugo el 13 de Abr. de 2020
Comentada: Stephen23 el 14 de Abr. de 2020
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

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 13 de Abr. de 2020
Editada: Ameer Hamza el 13 de Abr. de 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

Más respuestas (1)

Turlough Hughes
Turlough Hughes el 13 de Abr. de 2020
Editada: Turlough Hughes el 13 de Abr. de 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 documentation for scatter and colormap.

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by