0
votes

I would like to plot multiple lines on the same graph in matlab. I cant't find the easiest way to do it. At the moment I have something like this:

for j=1:n
plot(j,total,'*')
hold on
end

total changes in each iteration as well as j. This will make the plot I want but with the '*' instead of lines. I would like to join these asterisk with a line for each colour. Keep in mind that total is a vector with length k, thus in each iteration i have k asterisks.

For example:

iteration 1: j=1, total= [ 0.2000 0.6000 0.2000]'

iteration 2: j=2, total= [0.1000 0.6000 0.3000]'

iteration 3: j=3, total= [0.2095 0.4476 0.3429]'

X-axis is 1,2,3 and Y-axis should have 0.2,0.1,0.2095 connected with a line and an asterisks at these points, 0.6,0.6,0.4476 connected with a different colour line and asterisk etc.

4

4 Answers

3
votes

It seems that you want a different color for each line. In that case, I suggest:

figure
hold all
for j=1:n
    plot(j,total,'-*')
end

For the difference between hold all and hold on see http://www.mathworks.com/help/matlab/ref/hold.html

The information about how to specify line styles is here http://www.mathworks.com/help/matlab/ref/linespec.html

Based on the additional information about the data, sample code is:

nData = 3;
dataset = zeros(n,nData);
for j = 1:n
    dataset(j,:) = total';
end

x = 1:n;
plot(x,dataset,'-*');
legend('data set 1','data set 2','data set 3')

In this case hold is not required because all the data is plotted at once.

1
votes

You may find it easier to use lower level functions. Set up some axes and then generate a new line object (this is usually faster than recalling plot) on each iteration. The code below will generate a new line on the same set of axes for each iteration, coloring progressively from blue to red. I'm assuming that you can generate XVec from j each time:

myAx = axes;
for j=1:n
lineCol = [(j-1)/(n-1) 0 (1-((j-1)/(n-1)))];
line('XData',XVec(j,:),'YData',total,'color',lineCol,'linestyle','-','marker','*','Parent','myAx');
end

This removes the need for the hold command.

0
votes

Try:

plot(j,total,'-*');

The - before the * means use a line AND an asterisk.

Also, it would be neater to put the hold on before the start of the loop, since you only need it once.

0
votes

Put all data as columns in a matrix:

j = 1:5;

data1 = [1 2 3 4 5];
data2 = [5 4 3 2 1];
data3 = [4 6 2 8 3];

y = [ data1; data2; data3 ].';
plot(j,y)

This automatically sets different colors for each line