答案1
\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\tikzset{
dotted ends/.style={
draw=none,
postaction={
draw, decoration={lineto,
pre=moveto, pre length=0.05*\pgfmetadecoratedpathlength,
post=moveto, post length=0.05*\pgfmetadecoratedpathlength,
}, decorate},
postaction={
draw, dotted, decoration={lineto,
post=moveto, post length=0.95*\pgfmetadecoratedpathlength,
}, decorate},
postaction={
draw, dotted, decoration={lineto,
pre=moveto, pre length=0.95*\pgfmetadecoratedpathlength,
}, decorate},
}}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot[dotted ends, thick, blue, samples=50] {x^2};
\end{axis}
\end{tikzpicture}
\end{document}
遗憾的是,此解决方案不适用于该smooth
选项。
编辑:现在使用固定长度(0.5 厘米)的虚线部分,可以更好地处理不同长度的图:
\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\tikzset{
dotted ends/.style={
draw=none,
postaction={
draw, decoration={lineto,
pre=moveto, pre length=0.5cm,
post=moveto, post length=0.5cm,
}, decorate},
postaction={
draw, dotted, decoration={lineto,
post=moveto, post length=(\pgfmetadecoratedpathlength-0.5cm),
}, decorate},
postaction={
draw, dotted, decoration={lineto,
pre=moveto, pre length=(\pgfmetadecoratedpathlength-0.5cm),
}, decorate},
}}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot[dotted ends, thick, cyan, samples=500] {10+10*sin(500*x)};
\addplot[dotted ends, thick, blue, samples=50] {x^2};
\end{axis}
\end{tikzpicture}
\end{document}