# ContourPlot with BarLegend: vector format export problem

I have a couture plot which I want to export in vector format (e.g.PDF) and use in my latex. The example code from here:

plot = ContourPlot[Sin[x + y^2], {x, -3, 3}, {y, -2, 2},
Contours -> 8, BoundaryStyle -> Black,
PlotLegends ->
Placed[BarLegend[Automatic, LegendMarkerSize -> 150,
LegendFunction -> (Framed[#, RoundingRadius -> 5] &),
LegendLabel -> "Z"], {After, Top}], FrameLabel -> {"X", "Y"},
LabelStyle -> Directive[Black, Bold, Medium],  AspectRatio -> Full]


It looks fine on Adobe products, but on macOS preview, gostscript and other LaTeX editors built-in PFD viewers it seems like this:

This is actually a very common problem and there are already many similar posts:

I have tried all of them:

• From comments of this page I tried adding Method -> {"TransparentPolygonMesh" -> True}
• From here I tried Style[plot, Antialiasing -> False]
• From this page I tried /. {EdgeForm[], r_?(MemberQ[{RGBColor, Hue, CMYKColor, GrayLevel}, Head[#]] &), i___} :> {EdgeForm[r], r, i} this lessens the issue but white lines are still there:

• Using contourRegionPlotfunction defined here solves the issue, however it removes the BarLegend in the format I want!

I would appreciate if you could help me solve the issue.

Use cleanContourPlot from one of the threads you linked. It does not always work, but it can handle your example very well.

Without legends, a plot has the structure Graphics[...]. With legends, it has the structure Legended[Graphics[...], ...]. Therefore cleanContourPlot must be used only on the first part of Legended.

Head[plot]
(* Legended *)

fixedPlot = MapAt[cleanContourPlot, plot, {1}]


Avoid resizing figures with plots when exporting:

SetOptions[\$FrontEndSession, PrintingStyleEnvironment -> "Working"]


This setting will keep its effect until you restart the front end.

Export["plot.pdf", fixedPlot]

• I updated the cleanContourPlot function now so it would work automatically on Legended. – Szabolcs Sep 6 '17 at 11:17
• Novice here, would you mind ELI5? – Foad Sep 6 '17 at 11:17
• @Foad I don't understand "ELI5" – Szabolcs Sep 6 '17 at 11:24
• @Foad I do not have time to fix it now. I would use some quick and dirty workaround like Epilog -> {FaceForm[], EdgeForm[Black], Rectangle[{-3, -2}, {3, 2}]} where I took the rectangle dimensions from the ContourPlot variable bounds. – Szabolcs Sep 6 '17 at 12:42
• @Foad Can you plot the RegionFunction separately and superimpose? E.g. if you have x^2+y^2 < 5 then ContourPlot[x^2+y^2 == 5, ...] with black style and superimpose with Show. – Szabolcs Sep 6 '17 at 12:46