【问题标题】:Defining specific color and line type for each curve in a loop in MATLAB在 MATLAB 中为循环中的每条曲线定义特定的颜色和线型
【发布时间】:2020-04-07 17:39:55
【问题描述】:

通过在循环中绘制每条曲线与the previous question中自己存储的数据(即方法)相关的曲线,如何更改和定义新的特定颜色和线型(例如“--” ) 循环后每个方法的曲线?

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');

为了方便实现,每个方法的数据可以假设为rand(256x2)

【问题讨论】:

  • 您可以遍历坐标区对象的所有“子对象”以找到绘图对象,并从那里设置它们的“颜色”

标签: matlab for-loop matlab-figure


【解决方案1】:

您可以使用lines_obj = findobj(h, 'Type', 'Line')set(lines_obj, ...

例子:

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', '--');

结果:


如果您需要为每条线设置不同的样式,并且您需要将特定类型匹配到特定的情节......

在绘图时保留一个线对象数组,并使用 for 循环:

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

结果:

【讨论】:

  • 感谢您的解决方案。用哪个命令可以改变每条曲线的线宽?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多