Search code examples
matlabmatlab-figurergbfigure

Matlab plot3 line color setting


I want to plot a three-dimensional line chart using the plot3 function in matlab. The following code works to plot the lines with specified colour names 'r','g','k', etc. However, it gives an error when I replace the first colour by 'myGreen' using the RGB triplet: 'Error using plot3 Vectors must be the same length.'
How can I resolve this issue?

[xx,zz]=meshgrid(1:230,1:4);
x1=(xx(1,:));
x2=(xx(2,:));
x3=(xx(3,:));
x4=(xx(4,:));

z1=(zz(1,:));
z2=(zz(2,:));
z3=(zz(3,:));
z4=(zz(4,:));

yy=rand(230,4);
y1=(yy(:,1));
y2=(yy(:,2));
y3=(yy(:,3));
y4=(yy(:,4));

% custom colour 
myGreen=[0 0.5 0];
index={'data1','data2','data3','data4'}

figure
% It works and produces the attached figure
plot3(x1',z1',y1','r',x2',z2',y2','m', x3',z3',y3','b',x4',z4',y4','k')
% It doesn't work
plot3(x1',z1',y1','Color',myGreen,x2',z2',y2','m', x3',z3',y3','b',x4',z4',y4','k')

set(gca,'YTick',1:4,'YTickLabel',index)
grid on
xlabel('xlabel','FontSize',10);
zlabel('zlabel','FontSize',10)
axis tight

 

enter image description here


Solution

  • As per plot3 documentation, the function accepts a number of syntaxes:

    plot3(X,Y,Z)
    plot3(X,Y,Z,LineSpec)
    plot3(X1,Y1,Z1,...,Xn,Yn,Zn)
    plot3(X1,Y1,Z1,LineSpec1,...,Xn,Yn,Zn,LineSpecn)
    plot3(___,Name,Value)
    etc...
    

    The working line from the example:

    plot3(x1',z1',y1','r',x2',z2',y2','m', x3',z3',y3','b',x4',z4',y4','k')
    

    corresponds to the syntax

    plot3(X1,Y1,Z1,LineSpec1,...,Xn,Yn,Zn,LineSpecn)
    

    In the non-working line you've effectively substituted LineSpec1 ('r') with the Name,Value pair 'Color',myGreen. But there is no syntax plot3(X1,Y1,Z1,Name,Value,...,Xn,Yn,Zn,LineSpecn).

    Name,Value pairs are only accepted at the end of the argument list and apply to all series. You can achieve what appears to be the intended behavior by splitting up the calls to plot3 and using hold to keep them all on the same axes:

    plot3(x1',z1',y1','Color',myGreen)
    hold on
    plot3(x2',z2',y2','m')
    plot3(x3',z3',y3','b')
    plot3(x4',z4',y4','k')