Search code examples
matlabfor-loopmatlab-figure

Defining specific color and line type for each curve in a loop in MATLAB


By plotting the curves in a loop that each curve is related to its own stored data (i.e. method) in the previous question, how is it possible to change and define a new specific color and line type (e.g. "--") for each method's curve after the loop?

figure
hold on
for m = 1:length(methods)
  prFileName = strcat(readpath,dataset, '_', methods{m}, '_PRCurve.txt');
  R = load(prFileName);
  precision = R(:, 1);
  recall = R(:, 2);
  plot(recall, precision,'color',methods_colors(m,:),'linewidth',2);    
end
axis([0 1 0 1]);
hold off
grid on;
box on;
legend('methode one','method two')
xlabel('Recall','fontsize',12);
ylabel('Precision','fontsize',12);
set(gcf,'color','w');  %Background color
ax = gca;  % current axes
ax.GridLineStyle='-';
ax.GridAlpha=0.7;
ax.XAxis.LineWidth=4;
ax.YAxis.LineWidth=4;
Grid.LineWidth = 3;
set(gca,'FontName','Arial','FontWeight','bold');

For convenience in implementation, each method's data can be assumes as rand(256x2).


Solution

  • You can use lines_obj = findobj(h, 'Type', 'Line'), and set(lines_obj, ....

    Example:

    h = figure;
    
    %Plot something
    x = -6:0.1:6;
    plot(x, sin(x), x, cos(x), x, sin(x.^2), x, cos(x.^2));
    
    %Find all lines in figure
    lines_obj = findobj(h, 'Type', 'Line');
    
    %Set style of all lines to '--'
    set(lines_obj, 'LineStyle', '--');
    

    result:
    enter image description here


    In case you need to set different style for each line, and you need to match as specific type to specific plot...

    Keep an array of line objects while plotting, and use a for loop:

    close all
    
    g = gobjects(4); %Initialize and array with 4 graphics objects.
    
    x = -6:0.1:6;
    g(1) = plot(x, sin(x), 'r');hold on %Keep returned object in g(1)
    g(2) = plot(x, cos(x), 'g'); %Keep returned object in g(2)
    g(3) = plot(x, sin(x.^2), 'b');
    g(4) = plot(x, cos(x.^2), 'y');
    
    %Cell array of styles.
    styles = {'-', '--', ':', '-.'};
    
    %Array of width values
    widths = [0.5, 1, 1.5, 2];
    
    %Modify the style of each line:
    for i = 1:length(g)
        g(i).LineStyle = styles{i};
        g(i).LineWidth = widths(i);
    end
    

    Result:
    enter image description here