I'd like to draw something like the following (which was done in Mathematica) in pgfplots, but I can't find a way to define a piecewise linear function and have pgfplots get the full and empty circles correct. I could probably get something close by doing a constant plot with right marks, but it feels like there's probably a better way to do it directly. Any ideas appreciated.
-
1It looks like what you have is pretty good!– Paul StiversonJun 22, 2015 at 15:13
-
Thanks, but I did the above with Mathematica not pgfplots -- sorry for the confusion. I'll mention that in the question.– ShaneJun 22, 2015 at 15:13
-
Possible duplicate: "What is the clearest way to graph a piecewise function?".– DJPJun 22, 2015 at 15:19
-
Indeed -- thanks for sharing that DJP.– ShaneJun 22, 2015 at 15:34
1 Answer
Two ways: first, definig a function and plotting each piece separately, as was suggested in What is the clearest way to graph a piecewise function?; second , using two plots (the first approach might seem an overkill here):
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x) = (\x<0.5) * (1) + and(\x>0.5, \x<1) * (0);
}
]
\begin{axis}[
axis lines=middle,
enlargelimits
]
\foreach \start/\end in {0/0.5, 0.5/1}
\addplot[domain=\start:\end,blue,thick,samples=10] {func(x)};
\draw[blue,fill=blue]
(axis cs:0.5,1) circle (2pt);
\draw[blue,fill=white]
(axis cs:0.5,0) circle (2pt);
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
enlargelimits
]
\foreach \start/\end/\Func in {0/0.5/1, 0.5/1/0}
\addplot[domain=\start:\end,blue,thick,samples=10] {\Func};
\draw[blue,fill=blue]
(axis cs:0.5,1) circle (2pt);
\draw[blue,fill=white]
(axis cs:0.5,0) circle (2pt);
\end{axis}
\end{tikzpicture}
\end{document}
The filled and "empty" dots can be produced using small circles placed at the desired location using the axis
cs coordinate system. If you want to see the axis beneath the empty dot, add axis on top
:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[
declare function={
func(\x) = (\x<0.5) * (1) + and(\x>0.5, \x<1) * (0);
}
]
\begin{axis}[
axis lines=middle,
enlargelimits,
axis on top
]
\foreach \start/\end in {0/0.5, 0.5/1}
\addplot[domain=\start:\end,blue,thick,samples=10] {func(x)};
\draw[blue,fill=blue]
(axis cs:0.5,1) circle (2pt);
\draw[blue,fill=white]
(axis cs:0.5,0) circle (2pt);
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
enlargelimits,
axis on top
]
\foreach \start/\end/\Func in {0/0.5/1, 0.5/1/0}
\addplot[domain=\start:\end,blue,thick,samples=10] {\Func};
\draw[blue,fill=blue]
(axis cs:0.5,1) circle (2pt);
\draw[blue,fill=white]
(axis cs:0.5,0) circle (2pt);
\end{axis}
\end{tikzpicture}
\end{document}