[Tex/LaTex] How to plot max/min function in LaTeX

pgfplotstikz-pgf

I hope to plot max/min function automatically in tiki or pgfplots, meaning no manually split the whole graph into nice functions and plot them with respect to their domain. A specific example is to simply plot min(2*x,3*y). I tried to plot it using a contour map approach:

\documentclass{standalone}
\usepackage{pgfplots}

\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}
  \begin{axis}
    \addplot+[mark=none] function[raw gnuplot] {
      set contour base;
      set cntrparam levels discrete 0.0;
      unset surface;
      set view map;
      set isosamples 500;
      splot min(3*x,2*y);
    };
  \end{axis}
\end{tikzpicture}

\end{document}

But this fails completely, what is wrong?

If pgfplots cannot do it, is it possible to use existing libraries to generate tikz code for the graph of the function plotted in other programming languages. I know we have tikiDevice in R, but can we plot max min functions in R? More importantly, are there any better CAS system that would generate graphs of implicit functions and output tikz code? (I want to be able to label points on the function)

Best Answer

You can only plot using x. Your input is x, and y is plotted relative to that. You are plotting y=3*x (based on code), but you cannot graph y=2*y. Do you want x=2*y? Then you plot y=x/2, or enter x/2. For positive numbers, x/2 will always be smaller than x*3, but they will be equal at 0, and reverse for negative numbers.

You can also plot shapes like circles, but you still need to put it in terms of x. If you wanted to plot x^2 + y^2 = 2, you would plot y = (2-x^2)^.5 (and minus that - for y below 0).

\documentclass{standalone}
\usepackage{pgfplots}

\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}[domain=-8:8]

\begin{axis}
\addplot[draw=red]{3*x};
\addplot[draw=blue]{x/2}; % this is the same as x = y*2
\addplot[draw=green]{min(3*x,x/2)-.5};% subtracted 0.5 to not overlap
\end{axis}

\end{tikzpicture}

\end{document}

enter image description here

If you're truly looking for a 3d plot, where x and y are plotted against z, you might want something like this (I may have misunderstood the question).

\documentclass{standalone}
\usepackage{tikz,pgfplots}

\pgfplotsset{compat=newest}

\begin{document}

\begin{tikzpicture}
   \begin{axis}[samples=10,view={30}{45}]
    \addplot3[surf, domain=-2:2] {min(x*3,y*2)};
   \end{axis}
\end{tikzpicture}

\end{document}

enter image description here