# TikZ: Plot contour lines

by FKranhold   Last Updated July 28, 2018 10:23 AM

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

Tags :

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}


marmot
June 03, 2018 17:21 PM

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,
]
{
unset surface;
set cntrparam levels discrete -1,1;
set contour;
set yrange [-3:3];
splot [x=-3:3] x**2-x*y;
};
\end{axis}
\end{tikzpicture}
\end{document}


Mike
June 04, 2018 00:28 AM

## elliptic abacus

Updated June 05, 2015 01:10 AM