# how to draw $|x-2|$ with tikz？

\begin{tikzpicture}[domain=-.5:3]
\draw[->](-.2,0)--(3.2,0) node[below] {$x$};
\draw[->](0,-2.5)--(0,1.2) node[left] {$y$};
\draw[color=blue] plot(\x,abs(2-\x)) node[left] {$y=|x-2|$};
\end{tikzpicture}


It's not correct.

I try to draw two lines 2-x and x-2 in different domain. But I fail.

Similarly, how to draw f(x)=1 (x>0), f(x)=0 else these piecewise functions?

-
You're missing a {} on the y coordinate of the plot operation: the last \draw should be \draw[color=blue] plot(\x,{abs(2-\x)}) node[left] {$y=|x-2|$}; –  Herr K. Dec 9 '13 at 5:23
You can use pgfplots for this. –  OSjerick Dec 9 '13 at 5:28
\draw[color=blue] (-.5,2.5)--(2,0)--(3,1); –  Andrew Kepert Dec 9 '13 at 5:32

## 1 Answer

The plot is incorrect because the number of samples taken to draw the function is little. Take a large number of samples or use a different domain that allows x=2, TikZ plot path operation and Pgfplots takes 25 samples by default. Here a solution using Pgfplots:

# Code

\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}%http://www.ctan.org/pkg/pgfplots
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
domain = -.5:3,
samples = 50,
axis x line = center,
axis y line = center,
xlabel = {$x$},
ylabel = {$y$},
ticks = none
]
\addplot[blue] {abs(x-2)} [yshift=3pt] node[pos=.95,left] {$y=|x-2|$};
\end{axis}
\end{tikzpicture}
\end{document}


# Result

Applying the solution of KevinC's comment and plot[samples=50] can modify your idea to graph the function correctly.

Similarly, you can use different addplot with different domains to plot piecewise functions, as follows:

\begin{tikzpicture}
\begin{axis}[%
axis x line = center,
axis y line = center,
xlabel = {$x$},
ylabel = {$y$},
ymax = 2,
ticks = none
]
\addplot[domain=-3:0,blue] {0};
\addplot[domain=0.01:4,blue] {1};
\end{axis}
\end{tikzpicture}


Additionally, if you want to change the axis label position to outside of the axis, just add this options to the axis environment options:

every axis x label/.style={at={(current axis.right of origin)},anchor=north west},
every axis y label/.style={at={(current axis.above origin)},anchor=north east}

-
You can also do samples at={-.5,2,3} which only evaluates three points to draw this plot. –  Qrrbrbirlbel Dec 12 '13 at 5:27