Garrapatas de BarLegend distorsionadas en MatrixPlot

Sep 04 2020

Como se muestra en muchos hilos aquí ( this , this , ...), Tickses una opción válida de BarLegend. Pero no parece funcionar bien de esta manera MatrixPlot. Algunas marcas simplemente faltan y 0.5 obviamente no está en su lugar correcto (color). Tenga en cuenta que quiero el gráfico predeterminado con marcas personalizadas. ¿Qué me falta aquí o alguna solución?

data = Table[Sin[x] Cos[y], {x, 0, 2 Pi, 0.01}, {y, 0, 2 Pi, 0.01}];
MatrixPlot[data, 
 PlotLegends -> BarLegend[Automatic, "Ticks" -> {-0.5, 0, 0.5}], 
 LabelStyle -> Large]

Actualizar:

un caso más general con rango de datos asimétrico

data = Table[Sin[x] Cos[y] + 0.05 x y, {x, 0, 2 Pi, 0.01}, {y, 0, 2 Pi, 0.01}]; 
MatrixPlot[data, PlotLegends -> BarLegend[Automatic, "Ticks" -> {-0.2, 0.5, 1.1}], 
LabelStyle -> Large]

Respuestas

9 kglr Sep 04 2020 at 07:04

Actualización: la función Graphics`ArrayPlotDump`Private`HybridRankingAndNaturalScalerealiza el misterioso "escalado basado en una mezcla de valor relativo y clasificación para cada elemento de la matriz" . Construimos una función de escalamiento por partes ( reScale) mpReScaley la usamos para especificar el valor de la opción para "Ticks":

ClearAll[reScale,  cfMinMax]
reScale[{min_, max_}, {cfmin_, cfmax_}]  := 
  If[# < 0, Rescale[#, {min, 0}, {cfmin, 1/2}], Rescale[#, {0, max}, {1/2, cfmax}]] &;

cfMinMax = MinMax @ Graphics`ArrayPlotDump`Private`HybridRankingAndNaturalScale[
   Union @ SparseArray[#]["NonzeroValues"], 0., {0, 1}, .5] &;

Ejemplos:

data = {{1, 2, 1}, {2, 0, 1}, {0, -5, -1}};
ticks = {-4, -2, 3/2, 2};

cfminmax = cfMinMax[data];
minmax = MinMax @ data;
 
Row[{MatrixPlot[data, ImageSize -> 400, 
   PlotLegends -> BarLegend[Automatic], LabelStyle -> 16, 
   PlotLabel -> "default"], 
  MatrixPlot[data, ImageSize -> 400, 
   PlotLegends -> BarLegend[Automatic, 
     "Ticks" -> (Transpose[{reScale[minmax, cfminmax] /@ #, #}] & @ ticks)], 
   LabelStyle -> 16, 
   PlotLabel -> Row[{"Ticks : ", ticks}]]}, Spacer[10]]

Un aparte: podemos usar otra opción no documentada para especificar etiquetas de marca.

BarLegend[Automatic, "TickLabels" -> ticks, 
    "Ticks" -> (reScale[minmax, cfminmax] /@ ticks)]

para obtener la imagen en el segundo gráfico de arriba.

Cambiar datay tickspara

data = Table[Sin[x] Cos[y], {x, 0, 2 Pi, 0.01}, {y, 0, 2 Pi, 0.01}];
ticks = {-0.5, 0, 0.5};

Llegar

Usando el segundo ejemplo en OP:

data = Table[Sin[x] Cos[y] + 0.05 x y, {x, 0, 2 Pi, 0.01}, {y, 0, 2 Pi, 0.01}];
ticks = {-0.2, 0.5, 1.1};

obtenemos

Con

data = 1. + Table[Sin[x] Cos[y] + 0.05 x y, {x, 0, 2 Pi, 0.01}, {y, 0, 2 Pi,  0.01}] ;
ticks = {0.1, 0.5, 1.1, 2};

obtenemos

Respuesta original:

Esto parece estar relacionado con la forma especial en que se realiza el escalado MatrixPlotcomo se menciona en MatrixPlot >> Detalles y opciones

En el caso de OP, la solución más fácil es cambiar la especificación de tick a Transpose[{Rescale[#, {-1, 1}, {0, 1}], #} &@{-0.5, 0, 0.5}]:

MatrixPlot[data, 
 PlotLegends -> 
  BarLegend[Automatic, 
   "Ticks" -> Transpose[{Rescale[#, {-1, 1}, {0, 1}], #} & @ {-0.5, 0, 0.5}]], 
 LabelStyle -> Large]

Como solución alternativa (más general), use la función de color predeterminada con un argumento reescalado y la opción ColorFunctionScaling -> False:

defaultCF = "DefaultColorFunction" /.
    (Method /. Charting`ResolvePlotTheme[Automatic, MatrixPlot])
 Blend[System`PlotThemeDump`$ThemeDefaultMatrix, #1] &
MatrixPlot[data, 
 ColorFunction -> (defaultCF[Rescale[#, {-1, 1}]] &), 
 ColorFunctionScaling -> False, 
 PlotLegends -> BarLegend[Automatic, "Ticks" -> {-0.5, 0, 0.5}], 
 LabelStyle -> Large]

Alternativamente, especifique la función de color en BarLegend:

MatrixPlot[data, 
 PlotLegends -> BarLegend[{defaultCF[Rescale[#, {-1, 1}]] &, {-1, 1}}, 
   ColorFunctionScaling -> False, "Ticks" -> {-0.5, 0, 0.5}], 
 LabelStyle -> Large]

3 xzczd Sep 07 2020 at 08:38

kglr ya ha resuelto el problema, aquí hay solo un análisis adicional y otra posible solución.

En primer lugar, no creo que esto es un error, becauce por defecto MatrixPlotsabe cómo configurar adecuado Tickspara BarLegend:

plot = MatrixPlot[data, ImageSize -> 400, PlotLegends -> Automatic]

Mirando en el plot, encontramos que:

plot[[2, 1]] // InputForm
(*
BarLegend[{Blend[System`PlotThemeDump`$ThemeDefaultMatrix, #1] & , 
  {0.2889327547713697, 1.}}, LabelStyle -> {}, 
 LegendLayout -> "Column", LegendMarkerSize -> 400, 
 Ticks -> {{0.39446607623278385, -0.5}, {0.5, 0.}, {0.3100389372190109, 
  -0.9}, {0.626985112913238, 0.5}, {0.753970225826476, 1.}, 
  {0.880955338739714, 1.5}, {0.9825434290703043, 1.9000000000000001}}, 
 "PinningPoint" -> 0.5, "SmoothRange" -> False, 
 Charting`TickSide -> Right, ColorFunctionScaling -> False]
 *)

Como podemos ver, los ticks de BarLegendestán establecidos por la Ticksopción indocumentada , trazamos los ticks:

autotick = Cases[plot[[2, 1]], (Ticks -> a_) :> a][[1]] // Sort

ListLinePlot[autotick]

No es difícil darse cuenta de que es una línea por partes, dividiéndose en {0.5, 0.}. Podemos verificar esto aún más con LinearModelFit:

LinearModelFit[autotick[[#]], {1, x}, x]["RSquared"] & /@ {;; 3, 3 ;;}
(* {1., 1.} *)

Por lo tanto, incluso si no somos conscientes de ello Graphics`ArrayPlotDump`Private`HybridRankingAndNaturalScale, podemos cambiar la escala de los ticks de la siguiente manera:

ticks = {-0.2, 0.5, 1.1}

Clear[rescale]
rescale[tick_List, rest__] := rescale[#, rest] & /@ tick
rescale[tick_?Positive, mysteryminmax_, {min_, max_}] := 
 Rescale[tick, {0, max}, {1/2, mysteryminmax[[2]]}]
rescale[tick_, mysteryminmax_, {min_, max_}] := 
 Rescale[tick, {min, 0}, {mysteryminmax[[1]], 1/2}]

plot /. (Ticks -> _) :> (Ticks -> {rescale[ticks, 
       Sequence @@ (autotick[[{1, -1}]]\[Transpose])], ticks}\[Transpose])