Search code examples
matlabplotmatlab-figurelinestyle

Plotting matrices and defining a LineStyle for i.e. every 3rd line


In my Code I use plot(x,y) where x and y are 16x12 matrices. Now I want to define style rules like for example 'the first two lines should be red, then two lines blue' or 'every 3rd line should be LineStyle --'.... I thought of defining a LineStyle and a Color-Array and ploting the matrices line by line with a for-loop or something like that, but I was wondering if there is a more elegant way to do it?


Solution

  • There is a LineStyleOrder axis property. So setting every third line to be dashed can be done like this:

    data = rand(9);
    set(gca, 'LineStyleOrder','-|-|--'); %// note you can replace '-|-|--' with {'-','-','--'} if you prefer
    hold on;
    plot(data);
    

    You can do the same for colour using the ColorOrder property so having the first 2 lines red and the next 2 blue (and then repeating) is

    set(gca, 'ColorOrder',[1 0 0; 1 0 0; 0 0 1;0 0 1]);
    

    However if you mix the two, it will only repeat after every 12 lines:

    set(gca,'ColorOrder',[1 0 0; 1 0 0; 0 0 1;0 0 1],...
            'LineStyleOrder','-|-|--')
    

    i.e. this will cycle through your specified ColorOrder within your LineStyleOrder (i.e. for each line style, it cycles through all the colours) so in this case the first two lines are solid red, the next tow are solid blue, the next two are solid red again, the next two are solid blue again then lines 9 and 10 will be dashed red and lines 11 and 12 will be dashed blue and then this pattern repeat.

    So using them individually will work (just make sure you use this in conjunction with hold on even if you're plotting it all in one go) but if you want to cycle through colours independently of line styles then you will have to loop.