# Make PlotStyle aware of the number of curves that are plotted

I am afraid I'm having an xy-problem, so I will try to start by describing my context.

I have a function that depends on two variables, one of which I call a parameter. I want to make a plot of the function for multiple values of the parameter, in order to visualize the smooth dependence on the parameter. To emphasize the smoothness, I also want the plots to gradually change color, say from Red to Blue.

My (example) code is below:

f[x_, m_] = PDF[ NormalDistribution[ m, 1 ], x ];
blendLst[ cc_, lst_] := Blend[ cc , #] & /@ Subdivide[ 0, 1, Length@lst - 1]

ms =  Range[ 0, 10]/2;
Plot[ Evaluate[Table[ f[x, m], { m , ms}]], { x , - 4, 9}, PlotStyle -> blendLst[ {Red, Blue}, ms] ]


In this code, I have to make the function that blends the colors aware of the number of curves to be plotted. In this example, this is sort of automatic, but I can imagine a situation in which the Table is evaluated separately. Then I'd have to plug the number manually. This goes against the rule to not repeat yourself and hence is error-prone.

Is there a way to define the color-blending function in a way that it'd require only the colors as arguments, but would somehow learn the total number of required colors from the context? So my desired function betterBlend would work somewhat like

Plot[ listOfFunctions, { x , - 4, 9}, PlotStyle -> betterBlend[ {Red, Blue}] ]

• @BobHanlon curiously, I don't evaluate the PlotStyle and still get the plot (imgur.com/a/avWOmFK). Commented Jun 15, 2023 at 21:06
• Yes, I think I was confused. Disregard. Commented Jun 15, 2023 at 22:10

ClearAll[betterBlend]
Plot[a_, b_, c___, betterBlend[clrs_], d___] ^:=
Plot[a, b, PlotStyle -> (Blend[clrs, #1] &) /@ Subdivide[Length[a] - 1], c, d]


Examples:

ms =  Range[ 0, 10]/2;

f[x_, m_] = PDF[NormalDistribution[m, 1 ], x];

funcs = Table[f[x, m], {m, ms}];


Stick betterBland[desiredBlendColors] anywhere after the second argument in Plot:

Plot[funcs, {x, -4, 9}, Frame -> True, betterBlend[{Red, Blue}], Axes -> False]


Replace betterBlend[{Red, Blue}] with betterBlend[{Red, Green, Blue}] to get

Replace betterBlend[{Red, Blue}] with betterBlend[{LightGray, Black}] to get

Replace betterBlend[{Red, Blue}] with betterBlend["Rainbow"] to get

Plot[Evaluate[Table[BesselJ[i, x], {i, ms}]], {x, 1, 10},
betterBlend["SolarColors"], Axes -> False, Frame -> True,
PlotLegends -> BarLegend[{"SolarColors", MinMax @ ms}, ms]]


• Wow, this is so simple and elegant. Commented Jun 16, 2023 at 5:47