Given a contour plot,

plt=ContourPlot[Sin[x y],{x,-1,1},{y,-1,1}] 

I can extract the values of the contour lines using,

Cases[Normal@plot, Line[pts_, ___] :> pts, Infinity]

and the contour values using,

Cases[FullForm[plot], Tooltip[{__}, b_] :> b, Infinity]}

However, I would like to get the contour value corresponding to each contour line (e.g. in the form {contour value, line}). If the contours are connected then this is easy since each line is in one-to-one relationship to the contour value and you can just use the ordering. However, if the contours are disconnected this is no longer the case. How would I go about finding this?


It seems like this might work. I think that the Lines are grouped with their values in Graphics, so that

list = Cases[Normal@plt, Tooltip[{__, a__Line}, b_] :> {a, b}, Infinity]

will do the trick. This will return a list where the last element is the value, and the previous elements are the Lines.

To check, note that

Framed@Graphics[{Most@#, Text[ToString[Last@#], {0, 0}]}] & /@ list // GraphicsRow


enter image description here

To get just the list of coordinates rather than the Lines, do

Cases[Normal@plt, Tooltip[{__, a__Line}, b_] :> {Sequence @@ First /@ {a}, b}, Infinity]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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