为循环生成的图手动添加图例
Adding a legend manually for a plot generated by a loop
我在 Matlab 中一次生成一个图,具体取决于循环中条件的满足程度:
for i=1:size(Ind,1)
if(Ind(i)==1)
c='ro';
elseif(Ind(i)==2)
c='bo';
elseif(Ind(i)==3)
c='go';
end
plot(i,Y(i),c) %plotting some other value with the color chosen.
hold on
end
如何为此添加图例条目?我想将索引位置(1,2 和 3)与图例中的红色、蓝色和绿色相关联。
谢谢!
由于理论上要创建大量绘图对象,因此最好创建 3 个绘图对象(每种颜色各一个)或创建 gscatter 图。众所周知,MATLAB 在处理大量绘图对象时速度很慢。
创建 3 个绘图对象(红色、绿色、蓝色)
Ind = ceil(rand(100,1) * 3);
Y = rand(100,1);
figure;
red_plots = plot(find(Ind == 1), Y(Ind == 1), 'ro', 'DisplayName', 'red');
hold on;
blue_plots = plot(find(Ind == 2), Y(Ind == 2), 'go', 'DisplayName', 'green');
green_plots = plot(find(Ind == 3), Y(Ind == 3), 'bo', 'DisplayName', 'blue');
title('Three Plots')
legend([red_plots, blue_plots, green_plots])
创建一个gscatter情节
figure;
s = gscatter(1:size(Ind, 1), Y, Ind);
set(s, 'Marker', 'o')
title('Scatter')
legend({'red', 'green', 'blue'})
如果您没有 gscatter
所在的统计工具箱,那么您可以随时使用原版 scatter
figure;
s = scatter(1:size(Ind, 1), Y, 'CData', Ind, 'Marker', 'o');
title('Scatter')
colormap(eye(3));
我在 Matlab 中一次生成一个图,具体取决于循环中条件的满足程度:
for i=1:size(Ind,1)
if(Ind(i)==1)
c='ro';
elseif(Ind(i)==2)
c='bo';
elseif(Ind(i)==3)
c='go';
end
plot(i,Y(i),c) %plotting some other value with the color chosen.
hold on
end
如何为此添加图例条目?我想将索引位置(1,2 和 3)与图例中的红色、蓝色和绿色相关联。
谢谢!
由于理论上要创建大量绘图对象,因此最好创建 3 个绘图对象(每种颜色各一个)或创建 gscatter 图。众所周知,MATLAB 在处理大量绘图对象时速度很慢。
创建 3 个绘图对象(红色、绿色、蓝色)
Ind = ceil(rand(100,1) * 3);
Y = rand(100,1);
figure;
red_plots = plot(find(Ind == 1), Y(Ind == 1), 'ro', 'DisplayName', 'red');
hold on;
blue_plots = plot(find(Ind == 2), Y(Ind == 2), 'go', 'DisplayName', 'green');
green_plots = plot(find(Ind == 3), Y(Ind == 3), 'bo', 'DisplayName', 'blue');
title('Three Plots')
legend([red_plots, blue_plots, green_plots])
创建一个gscatter情节
figure;
s = gscatter(1:size(Ind, 1), Y, Ind);
set(s, 'Marker', 'o')
title('Scatter')
legend({'red', 'green', 'blue'})
如果您没有 gscatter
所在的统计工具箱,那么您可以随时使用原版 scatter
figure;
s = scatter(1:size(Ind, 1), Y, 'CData', Ind, 'Marker', 'o');
title('Scatter')
colormap(eye(3));