How do I place legend keys above bars/next to lines in Tikz?

I want to follow best practices in plotting graphics using Tikz (see here http://www.eugenewei.com/blog/2017/11/13/remove-the-legend).

I'd like to 'remove the legend to become one': instead of placing legend keys in a small box below using the \legend command, I'd like to have them placed nicely above the individual bars/next to the lines in a line graph.

Is there any elegant way to do so/a kludge that works?

Thanks!

The bar charts can be done, as pointed out by John Kormylo and as is illustrated in this nice answer, by using nodes near coords. The lines are arguably even simpler: you only have to append the plot by node[right] {...}.

\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
\begin{tikzpicture}
\addplot[blue] {x} node[right]{$x$};
\addplot[red] {cos(x)} node[right]{$\cos(x)$};