# Putting opaque legend background over gridlines in ContourPlot

Consider the code:

  plot1 = ContourPlot[{x y == 2, x y == 6}, {x, 1, 4}, {y, 1, 4},
ContourStyle -> {Red, Blue}, GridLines -> Automatic, GridLinesStyle -> Black]

Legended[Show[plot1], Placed[LineLegend[{Red, Blue}, {"x * y  =  2", "x * y  =  6"},
LegendFunction -> (Framed[#, Background -> Opacity[0.7, White]] &)], {.25, .75}]]


In the output, the opacity of the background of the legend does not seem to be working over the gridline:

Whereas, the expected output is:

The second one has been generated using Plot function instead of ContourPlot.

(This is obviously an overly simplified example. For my original purpose, I need to use ContourPlot, and make the legend background opaque over the gridlines.)

Using Method -> {"GridLinesInFront" -> False}:

ContourPlot[{x y == 2, x y == 6}
, {x, 1, 4}, {y, 1, 4}
, ContourStyle -> {Red, Blue}
, GridLines -> Automatic
, GridLinesStyle -> Black
, Method -> {"GridLinesInFront" -> False}
, PlotLegends -> Placed[LineLegend[{Red, Blue}
, {"x * y  =  2", "x * y  =  6"}
, LegendFunction -> (Framed[#
, Background -> Opacity[0.7, White]] &)]
, {.25, .75}
]
]


• (+1) Just I am looking for! Dec 13, 2022 at 9:55
• It seems that the GridLines in ContourPlot delay drawing.

• Here is a working around. Using Mesh to draw gridlines.

plot1 = ContourPlot[x y - 2, {x, 1, 4}, {y, 1, 4},
ContourStyle -> Red, Mesh -> {5, 5}, MeshFunctions -> {#1 &, #2 &},
Contours -> {0}, ContourShading -> None];
plot2 = ContourPlot[x y - 6, {x, 1, 4}, {y, 1, 4},
ContourStyle -> Blue, Mesh -> {5, 5}, MeshFunctions -> {#1 &, #2 &},
Contours -> {0}, ContourShading -> None];
Legended[
Show[plot1, plot2],
Placed[LineLegend[{Red, Blue}, {"x * y  =  2", "x * y  =  6"},
LegendFunction -> (Framed[#,
Background -> Opacity[0.7, White]] &)], {.25, .75}]]