1
$\begingroup$

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:

Using ContourPlot

Whereas, the expected output is:

Using Plot

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.)

$\endgroup$

2 Answers 2

1
$\begingroup$

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}
   ]
 ]

enter image description here

$\endgroup$
1
  • $\begingroup$ (+1) Just I am looking for! $\endgroup$
    – cvgmt
    Dec 13, 2022 at 9:55
1
$\begingroup$
  • 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}]]

enter image description here

$\endgroup$

Your Answer

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

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