Edit by OP. Here is the full working code:
ClearAll["Global`*"];
coefficients = Table[{x, RandomReal[]}, {x, 0, 5}];
functions = #1 + Cos[#2 x] & @@@ coefficients;
p = Plot[Evaluate@functions, {x, -2 Pi, 2 Pi}, PlotRange -> {-2, 2}, PlotLegends -> ToString /@ coefficients];
memberQ = MemberQ[p[[1]], #, Infinity] & /@ p[[2, 1, 1]];
positions = Position[memberQ, False];
p[[2, 1, 1]] = Delete[p[[2, 1, 1]], positions];
p
p[[2,1,1]]
returns the list of graphics elements which correspond to the coloured curves. MemberQ
is used to test p[[1]]
(which is the displayed plot) as to which coloured curves are displayed. It returns a list of True
and False
values. I then use Position
to return the positions in p[[2,1,1]]
of the curves that are not displayed. Then I update p[[2,1,1]]
and finally re-display p
. Here is the result
Original post that solved most of the problem
I do not know how to do it properly but you can check if a color exists by doing
coefficients = Table[{x, RandomReal[]}, {x, 0, 5}];
functions = #1 + Cos[#2 x] & @@@ coefficients;
p = Plot[Evaluate@functions, {x, -2 Pi, 2 Pi}, PlotRange -> {-2, 2}, PlotLegends -> ToString /@ coefficients]
MemberQ[p[[1]], yourColor, Infinity]
you find the colours in the legend by checking p[[2,1,1,i,2]] for all valid i.
If the check returns False you can Delete the entry from the legend. You could use DeleteCases for that but i cannot get that to work right now for lack of time. In spirit it should look like:
p[[2,1,1]] = DeleteCases[p[[2,1,1]], MemberQ[p[[1]], #[[2,2]], Infinity]&]
but where there is a pattern instead of a test.