amit
amit

Reputation: 178451

Add legend to graph created iteratively

I am creating a graph iteratively from various data sets, and I try to add legend to it, but it fails.

colors = {'g','b','m','k','c'};
subplot(2,3,iii);
hold all;
for jjj=1:length(aggregation_methods),
    aggregate = all_aggregate{jjj};
    std_agg = all_std_agg{jjj};
    plot(coverages, aggregate, colors{jjj});
    h1 = errorbar(coverages,aggregate,std_agg,colors{jjj});
    set(h1,'linestyle','none')
end
plot(coverages, regular, 'r');
h1 = errorbar(coverages,regular,std_reg,'r');
set(h1,'linestyle','none')
title(datasets{iii});
xlabel('coverage');
ylabel('MSE');
legend('enhanced with clustering(k=4)','enhanced random split', 'regular we');

enter image description here

The graph seems to be generated just fine, it's just the legend that is failing.
I expect the colors of the legend to be (top-down): green, blue, red.

P.S. I also tried (and it didn't work):

legend({'enhanced with clustering(k=4)','enhanced random split', 'regular we'});

EDIT:

Inspired by this thread, I changed the code to use the 'DisplayName' property for each plot:

colors = {'g','b','m','k','c'};
names = {'enhanced with clustering(k=4)','enhanced random split', 'regular we'};
subplot(2,3,iii);
hold all;
for jjj=1:length(aggregation_methods),
    aggregate = all_aggregate{jjj};
    std_agg = all_std_agg{jjj};
    plot(coverages, aggregate, colors{jjj}, 'DisplayName', names{jjj});
    h1 = errorbar(coverages,aggregate,std_agg,colors{jjj});
    set(h1,'linestyle','none')
end
%plot(coverages,aggregate,'g',coverages ,regular,'r');
%h1 = errorbar(coverages,aggregate,std_agg,'g');
%set(h1,'linestyle','none')
plot(coverages, regular, 'r', 'DisplayName', names{length(aggregation_methods) + 1});
h1 = errorbar(coverages,regular,std_reg,'r');
set(h1,'linestyle','none')
%axis([0 1 0 max(mean(rc{iii}))]);
title(datasets{iii});
xlabel('coverage');
ylabel('MSE');
legend('show');

However, it yields the following legend, but I'd like to get rid of these 'dataX' strings. enter image description here

Upvotes: 1

Views: 141

Answers (1)

Guddu
Guddu

Reputation: 2447

a=[
1 2 3 
4 5 6
7 8 9
];
clist={'g','b','m'};

for i=1:3
    pt(i)=plot(a(i,:),'Color',clist{i});
    hold on;
end
b=[5 6 7];
pt(4)=plot(b,'Color','r');
legend([pt(1:2) pt(4)],{'line1','line2','line4'});

Upvotes: 1

Related Questions