MATLAB: How to set the color of text in a legend to match its corresponding line color in a MATLAB figure

colorlabel;markupMATLABtextext;

How can I change the color of the text for the legend so that each label matches its corresponding line color?

Best Answer

Legend text supports the use of TeX markup, which can set specific colors for each legend entry. The following code snippet shows an example:
x = -pi:pi/20:pi;
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,'-ro',x,y2,'-.b')
legend('\color{red} sin(x)','\color{blue} cos(x)')
In the above example, the colors are specified manually, which may be cumbersome if there are several plots or multiple figures. The example below shows how to programmatically obtain the correct colors after generating the plot above:
[h, ~, plots] = legend('sin(x)', 'cos(x)');
for idx = 1:length(h.String)
h.String{idx} = ['\color[rgb]{' num2str(plots(idx).Color) '} ' h.String{idx}]
end
Please note that the above is syntactically valid only in MATLAB R2014b and later releases. For earlier releases, the 'set' and 'get' functions must be used to modify the label's 'String' property. Here, 'h' is a handle to the Legend object and 'plots' is an array of the plotted Line objects. The for-loop gets the color of each line from 'plots', converts it into a string, and then reformats the existing label text with TeX markup to change the color appropriately. The following link describes TeX markup for legend text in further detail: