Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
Does cf = Function[z, RGBColor[RandomReal[z, 3]]] work better? – cormullion Dec 12 '13 at 14:10
up vote 10 down vote accepted

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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