How to create a legend with multiple colored squares?

Hey,
how can I create a legend for the background of the following plot?
I would like to have a textbox with 3 colored squares (like the background) and the related category.
Thanks for your help!!

 Accepted Answer

% Create an axe
hAxe = axes(...);
% Get your patches handles
hGreen = patch(hAxe, ...);
hYellow = patch(hAxe, ...);
hRed = patch(hAxe, ...);
% Add legend
legend(hAxe, [hGreen hYellow hRed], {'Green', 'Yellow', 'Red'})

5 Comments

Thank you! How can I position the legend in the right-top-corner?
Yes, with the property Location
legend(hAxe, [hGreen hYellow hRed], {'Green', 'Yellow', 'Red'}, ...
'Location', 'northeast')
Here a link to legend properties documention, you'll see you can custom your legend in several ways.
One last question: How can I add the Data of the figure to the same legend with a black line?
Thanks a lot!
% Create an axe
hAxe = axes(..);
% Get your patches handles
hGreen = patch(hAxe, ..);
hYellow = patch(hAxe, ..);
hRed = patch(hAxe, ..);
% Get your line handle
hData = plot(hAxe, ..)
% Add legend
legend(hAxe, [hGreen hYellow hRed, hData], {'Green', 'Yellow', 'Red', 'Data'}, ...
'Location', 'northeast')

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!