Stacked line plot legend color change
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
It seems to be working properly with random data here, see below.
Can you share the data you are working with, so I can reproduce the results you are getting? Use the paperclip button to attach.
%Random data
n = 10;
t = (1:n).';
a = zeros(n,1);
b = ones(n,1);
c = rand(n,1);
data = table(t, a, b, c);
vars = {["a" "b"], "c"};
s = stackedplot(data, vars, "XVariable", "t");
%Change color of lines in 1st plot
s.LineProperties(1).Color = hsv(2);
%Modify legend for the 1st plot
s.AxesProperties(1).LegendLabels = ["Yo", "Sup"];
%Display and set legend label for the 2nd plot
s.AxesProperties(2).LegendVisible = 'on';
s.AxesProperties(2).LegendLabels = {'This is a line plot'};
Marek
on 22 Nov 2023
Accepted Answer
More Answers (0)
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!


