\documentclass[border=3mm]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \usepgfplotslibrary{autonode} \begin{document} \begin{tikzpicture} \begin{axis}[ width=9cm, height=6cm, grid=both, auto node placement, auto node debug=summary, auto node algorithm=repair, auto node failure mode=allow-minimal-overlap ] \addplot[blue,thick,domain=0:4,samples=40] {x} \pgfplotsautonode[preferred pos=0.65,sloped=true]{$y=x$}; \addplot[red,thick,domain=0:4,samples=40] {4-x} \pgfplotsautonode[preferred pos=0.35,sloped=true]{$y=4-x$}; \end{axis} \end{tikzpicture} \end{document} .