Changing the colour of a legend on the fly

1 view (last 30 days)
Jason
Jason on 1 May 2015
Commented: Jason on 1 May 2015
How do I manually change the colours (all different) of all the items in a legend. I know how many there are (n). This is my attempt
hleg=findobj(gcf,'Tag','legend')
switch n
case 1
set(hleg, 'TextColor','r')
case 2
set(hleg, 'TextColor','b')
case 3
set(hleg, 'TextColor','r')
case 4
set(hleg, 'TextColor','k')
end
but it changes all of the items colour to the same colour.
  2 Comments
pfb
pfb on 1 May 2015
Edited: pfb on 1 May 2015
uhm, I think that there is only one color property for all the text in a legend.
Anyway your code would not work. Switch chooses one of the instructions based on the value of n.
In principle, you should use a loop over n instead of a switch. But as I say, as far as I know, there is no individual color for the (text) items in a legend.
The symbols are colored, but their color is "synchronized" with the corresponding data.
Jason
Jason on 1 May 2015
I plot my first data first, then add the legend, then plot second data and then add second legend but obtain the first and concatenate.
i.e
axes(handles.axes1)
colour='r'
plot(x,r,colour,'MarkerSize', 1, 'Marker','o','LineWidth',1)
legText=get(handles.editLegend,'String');
then for the second data:
legText='MyNewData';
txt1=get(legend(gca),'String');
txt1=[txt1,legText];
hleg=legend(txt1);
I do it this way because sometime I want 3 or 4 data sets, so I just concatenate.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!