3

I have a contour plot with a bar legend, and I'm trying to format the labels of the bar legend. But something funny is happening. Here is a basic example that illustrates my issue:

data = Flatten[Table[{x, y, Exp[-x - y]}, {x, 0, 10}, {y, 0, 10}], 1];
data = N[data];
myConts = {1.0534*10^-7,1.0523*10^-5, 0.1, 0.2};
myPlot = ListContourPlot[data, PlotRange -> All, Contours -> myConts, PlotLegends -> True]

That gives the following:

enter image description here

I want the labels on the Bar Legend to all be rounded to 0.01. So the 10^(-7) should be displayed as 0.00. I tried the standard trick I found online, using the following code:

data = Flatten[Table[{x, y, Exp[-x - y]}, {x, 0, 10}, {y, 0, 10}], 1];
data = N[data];
myConts = {1.0534*10^-7, 1.0523*10^-5, 0.1, 0.2};
myLegFunc[x_] := x /. {NumberForm[y_, {w_, z_}] :> NumberForm[y, {3, 2}]};
myPlot = ListContourPlot[data, PlotRange -> All, Contours -> myConts, PlotLegends -> {LegendFunction -> legFunc}]

This is the result:

enter image description here

As you can see, all numbers except the 10^(-7) are formatted properly, but the 10^(-7) is not formatted at all.

Even weirder, if I add another value to the contours of order 10^(-6), then the 10^(-6) and the 10^(-7) are formatted (though not how I want). For instance, the following code:

data = Flatten[Table[{x, y, Exp[-x - y]}, {x, 0, 10}, {y, 0, 10}], 1];
data = N[data];
myConts = {1.0534*10^-7, 2.40252*10^-6, 1.0523*10^-5, 0.1, 0.2};
myLegFunc[x_] := x /. {NumberForm[y_, {w_, z_}] :> NumberForm[y, {3, 2}]};
myPlot = ListContourPlot[data, PlotRange -> All, Contours -> myConts, PlotLegends -> {LegendFunction -> legFunc}]

gives this:

enter image description here

I really don't understand what is going on here. Anyone has ideas?

Ben
  • 249
  • 1
  • 5

1 Answers1

3

If you take a look at the InputForm of the legend, you'll see why your approach fails:

myPlot = ListContourPlot[data, PlotRange -> All, Contours -> myConts, 
  PlotLegends -> {LegendFunction -> 
     EchoFunction[InputForm]@*myLegFunc}]
(* ... Text[Row[{1.0534, Superscript[10, -7]}, "\[Times]"], ...] ... *)

As you can see, the problematic tick label is a custom construct, not a simple NumberForm wrapped number.

Knowing this, the fix becomes easy: We just add a second replacement rule that handles the case of scientific notation.

myLegFunc[x_] := 
  x /. {NumberForm[y_, {w_, z_}] :> NumberForm[y, {3, 2}], 
    Row[{m_, Superscript[b_, e_]}, "\[Times]"] :> NumberForm[m*b^e, {3, 2}]};

Now the tick looks like it should:

myPlot = ListContourPlot[data, PlotRange -> All, Contours -> myConts, 
  PlotLegends -> {LegendFunction -> myLegFunc}]

enter image description here

Lukas Lang
  • 33,963
  • 1
  • 51
  • 97
  • Thanks, it worked perflectly. I wasn't aware that I could use the EchoFunction to figure out the InputForm. I will be sure to use that in the future. – Ben Feb 25 '19 at 16:51