My interpretation of the question is that you want the label be shifted along an orthogonal line of the connection. This is what the built in edge label
provides you with. Otherwise, this can be achieved either by determining the slope by eyes or writing a style that measures the slope. Since the slope in this case is 45 degrees, the anchor must be at 45-90=-45
. With above it will be at -90
(modulo upside down flips). With an edge label
this is automatic. Nonetheless it might be worthwhile to recalculate this with calc
to convince ourselves that it is so.
\documentclass[tikz,border=3mm]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[Midlabel/.style={to path={
let \p1=($(\tikztotarget)-(\tikztostart)$),
\n1={atan2(\y1,\x1)}
in (\tikztostart) -- (\tikztotarget) node[midway,circle,anchor=\n1-90]{#1}
}}]
\begin{scope}[local bounding box=L]
\node (v2) at (-1,2) {$B$};
\node (v1) at (-2.5,0.5) {$A$};
\draw [->] (v1) -- node[midway,above]{$f$} (v2);
\node at (-2,1.4) {*};
\end{scope}
\begin{scope}[local bounding box=M,xshift=4cm]
\node (v2) at (-1,2) {$B$};
\node (v1) at (-2.5,0.5) {$A$};
\draw [->] (v1) -- node[midway,anchor=-45]{$f$} (v2);
\node at (-2,1.4) {*};
\end{scope}
\begin{scope}[local bounding box=R,xshift=8cm]
\node (v2) at (-1,2) {$B$};
\node (v1) at (-2.5,0.5) {$A$};
\draw[->,Midlabel={$f$}] (v1) to (v2);
\node at (-2,1.4) {*};
\end{scope}
\begin{scope}[local bounding box=E,xshift=12cm]
\node (v2) at (-1,2) {$B$};
\node (v1) at (-2.5,0.5) {$A$};
\draw[->] (v1) to[edge label={$f$}] (v2);
\node at (-2,1.4) {*};
\end{scope}
\path[font=\sffamily] (L.north) node[above]{original}
(M.north) node[above]{node anchor adjusted by hand}
(R.north) node[above]{with \texttt{Midlabel} style}
(E.north) node[above]{with \texttt{edge label}};
\end{tikzpicture}
\end{document}
As tikz-cd
uses edge label
s, there this is automatic. The difference comes from the fact that in the Midlabel
style the node shape is taken to be a circle, which as evenly spread angle anchors.
\documentclass{article}
\usepackage{tikz-cd}
\usetikzlibrary{calc}
\begin{document}
\tikzset{Midlabel/.style={to path={
let \p1=($(\tikztotarget)-(\tikztostart)$),
\n1={atan2(\y1,\x1)}
in (\tikztostart) -- (\tikztotarget) node[midway,circle,anchor=\n1-90]{#1}
}}}
\begin{tikzcd}
& A \\
B\arrow[ur,"f"] &
\end{tikzcd}
\begin{tikzcd}
& A \\
B\arrow[ur,"f"]\arrow[ur,Midlabel={$\scriptstyle f$}] &
\end{tikzcd}
\end{document}