7

In the plot produced by the following code, I want to draw a contour line for $f(x,y)=0.8$. Here $f(x,y)=\sin(x^2+y)$, however, actually we don't know $f$, we've got the data only.

data = Flatten[Table[{x, y, Sin[x^2 + y]}, {x, 0, 1, 0.1}, {y, 0, 1, 0.1}], 1];
ListDensityPlot[data, ImageSize -> Large, PlotLegends -> Placed[BarLegend[Automatic,LegendMargins -> {{0, 0}, {10, 5}}], Right], ColorFunction -> "Rainbow", FrameLabel -> {"x", "y"}, LabelStyle -> Directive[Bold, 20]]
xiaohuamao
  • 4,728
  • 18
  • 36

2 Answers2

8

Related Q/A: ListContourPlot: delete some contour lines, but keep the colors

In addition to Epilog (Harry's answer) or MeshFunctions (rahul's comment) you can also use ListContourPlot:

ListContourPlot [data, ImageSize -> 400, 
 Contours -> {{0.8, {Thick, Black}}, ##& @@ ({#, None} & /@ Range[Min@data, Max@data, .0025])}, 
 PlotLegends -> Placed[BarLegend[Automatic, LegendMargins -> {{0, 0}, {10, 5}}], 
   Right], ColorFunction -> "Rainbow", FrameLabel -> {"x", "y"}, 
 LabelStyle -> Directive[Bold, 20]]

enter image description here

An alternative way to use Epilog:

epilog = ListContourPlot [data, Contours -> {{0.8, Thick}}, ContourShading -> None][[1]];
ListDensityPlot[data, ImageSize -> 400, 
 PlotLegends -> Placed[BarLegend[Automatic, LegendMargins -> {{0, 0}, {10, 5}}], 
   Right], ColorFunction -> "Rainbow", FrameLabel -> {"x", "y"}, 
 LabelStyle -> Directive[Bold, 20], Epilog -> epilog]

enter image description here

kglr
  • 394,356
  • 18
  • 477
  • 896
4

Epilog Approach:

line = Take[#, 2] & /@Select[Flatten[
Table[{x, y, Sin[x^2 + y]}, {x, 0, 1, 0.01}, {y, 0, 1, 0.01}], 1],
Abs[#[[3]] - 0.8] < 0.002 &]

then:

data = Flatten[ Table[{x, y, Sin[x^2 + y]}, {x, 0, 1, 0.1}, {y, 0, 1, 0.1}], 1];
density = 
ListDensityPlot[data, ImageSize -> Large, PlotLegends -> 
Placed[BarLegend[Automatic, LegendMargins -> {{0, 0}, {10, 5}}], 
Right], ColorFunction -> "Rainbow", FrameLabel -> {"x", "y"}, LabelStyle ->Directive[Bold, 20], 
Epilog -> {Thick, Blue, Line[line]}]

output: enter image description here

Harry
  • 2,715
  • 14
  • 27