我想在 pgfplots 中绘制类似下图的东西(在 Mathematica 中完成),但我找不到定义分段线性函数的方法,也无法让 pgfplots 正确地得到实心圆和空心圆。我可能可以通过绘制带有正确标记的常数图来得到接近的结果,但感觉直接绘制可能有更好的方法。欢迎提出任何想法。
答案1
两种方法:首先,定义一个函数并分别绘制每个部分,如绘制分段函数图像最清晰的方法是什么?;第二,使用两个图(第一种方法在这里似乎有点过度):
\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}
可以使用axis
cs 坐标系将小圆圈放置在所需位置来生成实心点和“空”点。如果要查看空点下方的轴,请添加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}