Instead of adding a legend manually and making sure the colors are consistent, use the 'Tag' property for each plot to separate them. Then use the function add_legend to add a legend. The function groups all plots based on their Tag property, and give each group a separate color. It uses the Tag property values as labels in the legend.
I have included the function varycolor by Daniel Helmick:
Hannes Mogensen (2021). Add Legend Automatically Based on Tag Property Value (https://www.mathworks.com/matlabcentral/fileexchange/58456-add-legend-automatically-based-on-tag-property-value), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
Inspired by: varycolor
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!