7
$\begingroup$

Consider a BarLegend showing a smooth gradient, like this one:

SeedRandom[36]
data = RandomReal[{-0.5, 1}, 10]

BarLegend[{"SolarColors", MinMax[data]}]

enter image description here

I would like to have two extra tick marks showing the actual minimal and maximal values.

MinMax[data]
(* {-0.289979, 0.789597} *)

Is there a simple way to do this using BarLegend?


I guess I could just use a DensityPlot instead. Here's an example, with the CustomTicks package. But this is a bit too complicated to write up when one is in a hurry and doesn't have personal utility functions handy. Is there an easier way?

DensityPlot[y, {x, 0, 1}, {y, Min[data], Max[data]},
 PlotRangePadding -> None, ColorFunction -> "SolarColors", 
 AspectRatio -> 15,
 ImageSize -> {Automatic, 250},
 FrameTicks -> {{None, 
    Sort@Join[
      LinTicks[Min[data], Max[data], TickDirection -> Out, 
       MajorTickLength -> 0.2, 
       MinorTickLength -> 
        0.1], ({#, NumberForm[#, 2], {0, 0.2}, {}} &) /@ 
       MinMax[data]]}, {None, None}}
 ]

enter image description here

$\endgroup$

2 Answers 2

9
$\begingroup$

It looks like BarLegend takes Ticks as an undocumented option. With a helper function:

makeTicks[range_, num_] := Rescale[#, {1, num}, range] & /@ Range[num]

BarLegend[{"SolarColors", MinMax[data]}, Ticks -> makeTicks[MinMax[data], 7]]

Mathematica graphics

For more control, a more complicated function can be used:

makeTicks2[range_, num_] := 
 MapIndexed[{#1, 
    NumberForm[#1, If[(#2[[1]] == 1 || #2[[1]] == num), 2, 1]]} &, 
  Rescale[#, {1, num}, range] & /@ Range[num]]

BarLegend[{"SolarColors", MinMax[data]}, 
 Ticks -> makeTicks2[MinMax[data], 7]]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ Thanks! I kept trying FrameTicks ... $\endgroup$
    – Szabolcs
    Jan 12, 2018 at 20:16
4
$\begingroup$

Maybe

SeedRandom[36]
data = RandomReal[{-0.5, 1}, 10];

vals = Select[FindDivisions[MinMax@data~Join~{0.2}, 6], 
     IntervalMemberQ[Interval@MinMax@data, #] &]~Join~MinMax[data] // 
   Sort;

ticks = Transpose[{vals, NumberForm[#, 2] & /@ vals}];

BarLegend[{"SolarColors", MinMax[data]}, Ticks -> ticks]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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