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:

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

Tags : tikz-pgf plot


Answers 2


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

marmot
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,
]
\addplot gnuplot[raw gnuplot,thick,mark=none]
    {
        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}

enter image description here

Mike
Mike
June 04, 2018 00:28 AM

Related Questions


How to plot a simple circle in LaTeX

Updated November 13, 2016 08:09 AM

Plotting piecewise functions with TikZ

Updated March 27, 2015 05:07 AM

How to make the distances look equal?

Updated May 30, 2015 22:10 PM

Problem plotting in TikZ

Updated May 30, 2015 01:10 AM

elliptic abacus

Updated June 05, 2015 01:10 AM