[Tex/LaTex] TikZ: Plot contour lines

plottikz-pgf

I have a (continuous) function on the real plane (e. g. f(x,y)=x^2-x*y) and want to draw contour lines (e. g. f(x,y)=-1, f(x,y)=1 etc.). Furthermore, I want to adjust the region where to do this (e. g. on the square [-3,3]²). The resulting picture should look like this:

The desired plot

I know how to do this in MATLAB (using contour), but is there any possbility to do this in TikZ? A minimal example doing exactly this would be great!

(A further question: My actual function is the real part of a complex polynomial (e. g. f(z)=Re(z^2-1)). Of course, I can manually calculate it using z=x+iy, but is there an elegant way to use this complex term directly in TikZ?)

Best Answer

The pgfplots manual is full of examples for contour plots. UPDATE: I missed the fact that the contours are at +1 and -1. Big thanks to @Mike for pointing that out!

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{width=7cm,compat=1.16} 
\begin{document}
\begin{tikzpicture} \begin{axis}[
    title={$x^2-x\,y$},
    enlarge x limits,
    view={0}{90},
    xlabel=$x$, ylabel=$y$,
    small,
]
\addplot3[domain=-3:3,
        domain y=-3:3,
        contour gnuplot={levels={-1,1},labels=false},
        thick,samples=50,samples y=50,
    ] {x^2-x*y};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here