# TikZ: Plot contour lines

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:

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

• tikz, pgfplots as well any other programs can plot only real function. however, you can calculate parts of complex function, which you like to present by program with given equations. – Zarko Jun 3 '18 at 13:07
• @Zarko it could be done with parametric functions in pgfplots, or am I wrong on this? – Skillmon Jun 3 '18 at 13:11
• @Skillmon, to be honest, i don't know. however so far i didn't see diagram of complex function. always was split in two part: real and imaginary or amplitude and phase. how you do this is mater of your math skills (off-topic here). maybe is my math knowledge rusty :-) – Zarko Jun 3 '18 at 13:57

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


• If you change levels={1} to levels={-1,1}, you'll get the missing lines. – Mike Jun 4 '18 at 0:16

Since you have to use gnuplot anyway, you could also let it do all the number crunching. It is much faster, but of course, this requires some knowledge about gnuplot. In your case, you even have to use the option raw gnuplot.

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{width=7cm,compat=1.15}
\begin{document}
\begin{tikzpicture} \begin{axis}[
title={$x^2-x\,y$},
view={0}{90},
xlabel=$x$, ylabel=$y$,
small,
]