Mathematica Asked by sunt05 on August 13, 2021
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:
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?
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.
Correct answer by ybeltukov on August 13, 2021
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
Answered by Meir Bar-Tal on August 13, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP