Graphing a Piecewise Function
Graphing a Piecewise Function

Is it possible to graph a piecewise function using one \addplots line? Here is a MWE that demonstrates what I want to do:

\documentclass[tikz]{standalone} \usepackage{pgfplots} \begin{document} \begin{tikzpicture}[declare function={ g(\x)=\x<0 ? x+2 : 0.5*x-2;}] \begin{axis}[ grid=both, grid style={line width=0.35pt, draw=gray!75}, axis lines=center, axis line style={-}, xmin=-5, xmax=5, ymin=-5, ymax=5, ticklabel style={font=\footnotesize,inner sep=0.5pt,fill=white,opacity=1.0, text opacity=1}, every axis plot/.append style={line width=0.95pt, color=red, samples=500}, ] \addplot[domain=-5:0] {g(x)}; \addplot[domain= 0:5] {g(x)}; \end{axis} \end{tikzpicture} \end{document}

Ideally, I’d like to use \addplot[domain=-5:5] {g(x)}; with some kind of modification so that there isn’t a line between the end of the first half and beginning of the second half.

EDIT:
Below is the code that I’m actually tinkering with. I took the suggestion for samples at and defined the function to be inf anywhere where there was a jump discontinuity:

\documentclass[tikz]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.15} \pgfplotsset{soldot/.style={only marks,mark=*, line width=0.2pt, mark size=1.5pt}} \pgfplotsset{holdot/.style={fill=white,only marks,mark=*, line width=1.0pt, mark size=1.5pt}} \begin{document} \begin{tikzpicture}[declare function={ g(\x)=\x<-2 ? 1/(2*(\x+2))+3 : (\x==-2 ? inf : (\x< -1 ? 1/(\x+2)-2: (\x==-1 ? inf : (\x< 1 ? -\x^2+1: (\x< 3 ? 2*(\x-2)^2-2: -0.5*exp(-\x+3.7)+1))));}] \begin{axis}[ grid=both, grid style={line width=0.35pt, draw=gray!75}, axis lines=center, axis line style={black,-}, xmin=-5, xmax=5, ymin=-5, ymax=5, xtick={-6,-5,...,6}, ytick={-6,-5,...,6}, ticklabel style={font=\footnotesize,inner sep=0.5pt,fill=white,opacity=1.0, text opacity=1}, every axis plot/.append style={line width=0.95pt, color=red}, ] %% Using 'samples at' instead of domain to control plotting discontinuities \addplot[samples at={-5,-4.95,...,-2.005,-2,-1.95,...,-1.05,-1.005,-1,-0.95,...,5}, unbounded coords=jump] {g(x)}; \addplot[holdot] coordinates{(-1,0)(2,-2)}; \addplot[soldot] coordinates{(-1,-1)(2,-1)}; \draw[dashed, red, line width=0.95pt] ({axis cs:-2,0}|-{rel axis cs:0,0}) -- ({axis cs:-2,0}|-{rel axis cs:0,1}); \addplot[dashed, samples at={-5,-3}]{3}; \addplot[dashed, samples at={3,5}]{1}; \end{axis} \end{tikzpicture} \end{document}

You are watching: Graph a piecewise function with a jump. Info created by Bút Chì Xanh selection and synthesis along with other related topics.