2

Idea from @Jasper Habicht on this question: Plotting with LaTeX

How can one plot a function, so that the ends of the lines are automatic dotted like in this picture (green and blue functions):

Function with solid line that ends dotted

  • I am asking this question to have a place to post my own solution for future reference. Also it could be interesting to see other/better solutions. – hpekristiansen Dec 19 '22 at 22:10

1 Answers1

4
\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}

Graph of parabola with dotted ends

This solution does unfortunately not work with the smooth option.

Edit: now with fixed length(0.5cm) dotted section to better work with different length plots:

\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}

Parabola and sine function with dotted ends