So I will begin this question by linking to an existing unanswered question on the same matter: Link. I am unsure if I should revive the old question or post a new one, so I just ended up making a new post.
So the problem is that when you use the option \begin{tikzpicture}[trim axis left, trim axis right] along with a reference to a legend through the use of legend to name and \ref{} or \pgfplotslegendfromname{}, the legend position will be messed up.
I have provided an MWE below illustrating the issue.
Has anyone been able to find a good solution to this problem?
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.6}
\usepgfplotslibrary{groupplots}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}[trim axis left, trim axis right]%used for centering only axis and not ylabels etc
\begin{groupplot}[group style={group size=1 by 2, vertical sep=2.5cm},small]
\nextgroupplot[title=Plot 1, xlabel=$x$, ylabel=$y_1$,
legend entries={Entry 1,Entry 2,Entry 3}, legend to name=myLegends1, legend columns=3]
\addplot+[domain=0:360] {sin(x)};
\addplot+[domain=0:360] {sin(x)+1};
\addplot+[domain=0:360] {sin(x)+2};
\nextgroupplot[title=Plot 2, xlabel=$x$, ylabel=$y_2$]
\addplot+[domain=0:360] {cos(x)};
\end{groupplot}
\node[anchor=north] at (group c1r1.below south) {\pgfplotslegendfromname{myLegends1}};
\end{tikzpicture}%
\end{figure}
\begin{figure}
\centering
\begin{tikzpicture}%[trim axis left, trim axis right]%used for centering only axis and not ylabels etc
\begin{groupplot}[group style={group size=1 by 2, vertical sep=2.5cm}, small]
\nextgroupplot[title=Plot 1, xlabel=$x$, ylabel=$y_1$,
legend entries={Entry 1,Entry 2,Entry 3}, legend to name=myLegends2, legend columns=3]
\addplot+[domain=0:360] {sin(x)};
\addplot+[domain=0:360] {sin(x)+1};
\addplot+[domain=0:360] {sin(x)+2};
\nextgroupplot[title=Plot 2, xlabel=$x$, ylabel=$y_2$]
\addplot+[domain=0:360] {cos(x)};
\end{groupplot}
\node[anchor=north] at (group c1r1.below south) {\pgfplotslegendfromname{myLegends2}};
\end{tikzpicture}%
\end{figure}
\end{document}
The first figure shows the plot when the ´trim axis´ is active (here the legend is placed wrong). The second figure shows the plot without the trim axis and here the legend is placed correctly.


trim axishas no effect when used as done in the example by John Kormylo. The purpose of usingtrim axis, for me at least, is to make it possible to center just the axis instead of the entire picture (i.e., the axis with labels, ticks, etc.). If you add a caption to the figure environment, it will be easy to see that see that John's solution does not center the picture correctly (i.e., that it is equivalent to the case where notrim axisis performed at all). – HGC Aug 14 '20 at 06:36