# How can I have a single BarLegend in a grid of multiple DensityPlot, with color properly scaled in all plots relative to that coloured BarLegend?

I have an amplitude distribution function like :

amplitude[x_, y_, a_] = Exp[-a x^2 - Sin[y^2]];

Table[DensityPlot[amplitude[x, y, a], {x, -1, 1}, {y, -3, 3},
ColorFunction -> "Rainbow",
PlotLegends -> Automatic,
ImageSize -> Medium], {a, 1, 4, 1}]


and my results are :

I need a common color BarLegend for all multiple plots such that color distribution in all plots are properly scaled with respect to the the common colored BarLegend.

I have tried the solution offered on somewhat similar question. But the problem is that values of BarLegend is not PROPERLY connected with the colours of the DensityPlot.

\$Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global*"]

amplitude[x_, y_, a_] = Exp[-a x^2 - Sin[y^2]];


The range of amplitude values is

{min, max} = #[{amplitude[x, y, a],
-1 <= x <= 1, -3 <= y <= 3, 1 <= a <= 4}, {a, x, y}] & /@
{MinValue, MaxValue}

(* {1/E^5, E} *)


The approximate numeric values are

{min, max} // N

(* {0.00673795, 2.71828} *)

Prepend[
Partition[
Table[
DensityPlot[
amplitude[x, y, a], {x, -1, 1}, {y, -3, 3},
PlotLabel -> StringForm["a = ", a],
ColorFunction -> Function[{f},
ColorData["Rainbow"][(f - min)/(max - min)]],
ColorFunctionScaling -> False,
ImageSize -> Small],
{a, 1, 4, 1}],
2],
{BarLegend[{"Rainbow", {min, max}},
LegendLayout -> "Row",
LegendLabel -> Placed["amplitude", Before]],
SpanFromLeft}] //
Grid


• Great...@Bob Hanlon...Do I really need to find min-max of my function for proper coloring all plots or is it necessary to find min-max for all set of functions requiring DensityPlot. Commented Nov 17, 2022 at 6:21
• It is necessary for the different plots to share the same scale. If you have a single DensityPlot this is handled automatically. Commented Nov 17, 2022 at 6:32

NOTE: The following solution only seems to work - there is a single legend, but the different sub plots use different color schemes, so this doesn't really solve the question asked. I have submitted a report to WRI, so this will hopefully work as expected in the future

In newer versions (starting with 13.0), you can use a single DensityPlot together with the PlotLayout option:

amplitude[x_, y_, a_] = Exp[-a x^2 - Sin[y^2]];

DensityPlot[
Evaluate@Table[amplitude[x, y, a], {a, 1, 4, 1}],
{x, -1, 1}, {y, -3, 3},
ColorFunction -> "Rainbow", PlotLegends -> Automatic,
ImageSize -> Medium,
PlotLayout -> {"Row", 2}
]
`

• I may be wrong...but there is a bug in setting PlotLegend to automatic. Since in FIRST, SECOND & THIRD panel of your solution @Lukas Lang...the maximum value is NOT truly reflecting the properly scaled RED color. Commented Nov 17, 2022 at 10:26
• @KumarGauravSagar True... Something seems to be very wrong here - I'll file a report with WRI to hopefully get this fixed in the future. Commented Nov 17, 2022 at 10:54