带有虚线端点的 PGFplots 中的绘图函数

带有虚线端点的 PGFplots 中的绘图函数

@Jasper Habicht 对这个问题的看法:使用 LaTeX 绘图

如何绘制函数,使得线的末端自动变成虚线,就像这张图一样(绿色和蓝色函数):

带虚线的实线函数

答案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}

带点端的抛物线和正弦函数

相关内容