2

I would like to only plot my function f(x,y)=x^2-y^2 for the points x^2+y^2=<1 and if possible the rest with fill opacity=0.4.

\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{every axis/.style={scale only axis}}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[unit vector ratio*=1 1 1,
    title={$f(x,y)=x^2-y^2$}, 
    xlabel=$x$, ylabel=$y$,
    xmin=-1, xmax=1,
    ymin=-1, ymax=1,
    zmin=-1, zmax=1,
    3d box=complete,]
    \addplot3[surf, domain=-1:1] 
    {x^2-y^2};
    \end{axis}
    \end{tikzpicture}
\end{document}
Sebastiano
  • 54,118
Derr Herr
  • 359
  • 1
  • 7

1 Answers1

3

The constraint x^2+y^2\le 1 just means that you want to plot the function for values x and y inside the unit circle. This suggests to switch to polar coordinates.

\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\usepackage{tikz}
\pgfplotsset{every axis/.style={scale only axis}}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[unit vector ratio*=1 1 1,
    title={$f(x,y)=x^2-y^2$}, 
    xlabel=$x$, ylabel=$y$, 
    xmin=-1, xmax=1,
    ymin=-1, ymax=1,
    zmin=-1, zmax=1,
    3d box=complete,samples=30]
    \addplot3[surf,domain=0:sqrt(2),y domain=0:2*pi,opacity=0.4] 
    ({x*cos(deg(y)},{x*sin(deg(y)},{(x*cos(deg(y))^2-(x*sin(deg(y))^2});
    \addplot3[surf,domain=0:1,y domain=0:2*pi] 
    ({x*cos(deg(y)},{x*sin(deg(y)},{(x*cos(deg(y))^2-(x*sin(deg(y))^2});
    \end{axis}
    \end{tikzpicture}
\end{document}

enter image description here

UPDATE: For completeness: without polar coordinates.

\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}
\usepackage{tikz}
\pgfplotsset{every axis/.style={scale only axis}}
\begin{document}
    \begin{tikzpicture}
    \begin{axis}[unit vector ratio*=1 1 1,
    title={$f(x,y)=x^2-y^2$}, 
    xlabel=$x$, ylabel=$y$,
    xmin=-1, xmax=1,
    ymin=-1, ymax=1,
    zmin=-1, zmax=1,
    3d box=complete,%point meta=sqrt(x^2+y^2)
        ]
    \addplot3[surf, domain=-1:1, opacity=0.4]{x^2-y^2};
    \addplot3[surf, domain=-1:1, point meta={  abs(x^2+y^2)>1 ? nan : z
        }]{x^2-y^2};
    \end{axis}
    \end{tikzpicture}
\end{document}

enter image description here

In both examples, you can play with samples to make the plot somewhat smoother.

  • Is it possible to make it more smooth? – Derr Herr Jan 28 '18 at 21:24
  • @DerrHerr You can add samples=40 and also play with samples y. I must admit that I am not too happy with my solution since it only sort of works for this special situation. I was also playing with functions like 1-floor(min(x^2+y^2,1)) to cut off the graph, but the outcome is less appealing. And I am bit surprised to find that, unlike in asymptote, it seems not possible (?) to have custom domains here. –  Jan 28 '18 at 21:30