Stacked line plot legend color change
7 views (last 30 days)
Show older comments
I would like to change colors of the legend to match the line colors in the plot, however since legend options are fairly limited for stacked plots as it seems, I can't get it to work. I am running custom colors for the lines, but even when I am not, it only returns black lines for the legend. Any help or workaround is appreciated.
P=stackedplot(AL1,AL2,AL3,'DisplayLabels',["Burr [µm]" "Rounding [µm]"]);
title('Aluminium alloy samples')
xlabel('Process duration [min]')
P.AxesProperties(1).YLimits = [0 55];
P.AxesProperties(2).YLimits = [0 265];
grid on;
P.LineWidth = 1.25;
C = [0.3 0.5 0.7
0.2 0.7 0.7
0.1 0.9 0.7];
P.LineProperties(1).Color = C;
P.LineProperties(2).Color = C;
leg = getfield(struct(P),'LegendHandle');
leg(1).Orientation = 'Horizontal';
set(P.AxesProperties(1), 'LegendLocation', 'NorthEast');
P.AxesProperties(1).LegendVisible = 'on';
P.AxesProperties(1).LegendLabels = ["Sample 1","Sample 2","Sample 3"];

3 Comments
Accepted Answer
Dyuman Joshi
on 23 Nov 2023
Moved: Dyuman Joshi
on 23 Nov 2023
As you want to get the legend for individual chart(s) from a stackedplot of multiple tables/timetables, turn the "CollapseLegend" property of the corresponding axes to "off"
load('al_data.mat')
%Check the contents of the loaded data
whos
%Plot the stackedplot
P=stackedplot(AL1,AL2,AL3,'DisplayLabels',["Burr [µm]" "Rounding [µm]"]);
title("Aluminium alloy samples")
xlabel("Process duration [min]")
%Turn the stackedplot legend off
P.LegendVisible = "off";
ax = P.AxesProperties;
ax(1).YLimits = [0 55];
ax(2).YLimits = [0 265];
grid on;
P.LineWidth = 1.25;
C = [0.3 0.5 0.7
0.2 0.7 0.7
0.1 0.9 0.7];
P.LineProperties(1).Color = C;
P.LineProperties(2).Color = C;
%Display legend by disabling collapsing behaviour
ax(1).CollapseLegend = "off";
ax(1).LegendLabels = ["Sample 1","Sample 2","Sample 3"];
If you want to display the legend for the 2nd chart as well, follow the same commads for the 2nd axes.
You can adjust other legend properites as you like.
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


