9

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?

rcollyer
  • 33,976
  • 7
  • 92
  • 191
sunt05
  • 4,367
  • 23
  • 34

2 Answers2

12

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

Switch[Legending`LegendDump`colorfunction,
_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.

ybeltukov
  • 43,673
  • 5
  • 108
  • 212
0

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

AsukaMinato
  • 9,758
  • 1
  • 14
  • 40