I encountered a really strange problem with BarLegend. Say you have a user-defined color function:

cf[z_]:=RGBColor[RandomReal[z, 3]]

When you want to use it in BarLegend as below:

BarLegend[{cf, {1, 10}}]

Mathematica will generate a blank bar shown as below: enter image description here

However, after I change the function head in BarLegend to a pure function:

BarLegend[{cf[#]&, {1, 10}}]

Mathematica can give desired result.

I cannot figure out why Mathematica doesn't accept user-defined color function. Could anyone please give a clue?

  • 1
    $\begingroup$ Does cf = Function[z, RGBColor[RandomReal[z, 3]]] work better? $\endgroup$ – cormullion Dec 12 '13 at 14:10

If you look into the source code

ClearAttributes[BarLegend, ReadProtected]
?? BarLegend

And into nested functions (BarLegend,Charting`iBarLegend $\to$ Legending`LegendDump`iColorBandLegend $\to$ Legending`LegendDump`parseColorBand) you can find the following code

_String, ColorData[Legending`LegendDump`colorfunction]/@Legending`LegendDump`values,
_ColorDataFunction, Legending`LegendDump`colorfunction/@Legending`LegendDump`values,
_List, Switch[Legending`LegendDump`fn, Legending`ColorBandLegend,With[{Legending`LegendDump`list=Legending`LegendDump`colorfunction},Blend[Legending`LegendDump`list,#1]&]/@Legending`LegendDump`values,
BarLegend|_, Legending`LegendDump`iter=Max[Length[Legending`LegendDump`colorfunction]-Length[Legending`LegendDump`values],0];Do[Legending`LegendDump`colorfunction=Reverse[Charting`padList[Legending`LegendDump`colorfunction,Length[Legending`LegendDump`colorfunction]-1]],{Legending`LegendDump`iter}];If[OddQ[Legending`LegendDump`iter],Reverse[Legending`LegendDump`colorfunction],Legending`LegendDump`colorfunction]],
Hue|GrayLevel, (Legending`LegendDump`colorfunction[#1]&)/@Legending`LegendDump`values,
_Function, Legending`LegendDump`colorfunction/@Legending`LegendDump`values,
_, Return[{}]]

It shows that the function must have the Function header.

  • $\begingroup$ So could you provide a working example please? $\endgroup$ – Tom Sep 24 '19 at 11:51

With this response I tried:

maxmin = {10, 20};
BarLegend[{Function[x, Hue[0.8 Rescale[x, maxmin]]], maxmin}]

which worked nicely to truncate the Hue function to remove the red at the top


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.