[Tex/LaTex] Centering caption in figure environment with a tikzpicture

captionspgfplotstikz-pgf

I'm trying to center a tikzpicture and a caption inside the figure environment, but when I compile something is off. It seems as if the caption and the tikzpicture are centering with respect to diferent referenes. I'm using Overleaf.

\begin{figure}[H]
\centering
\begin{tikzpicture}[scale=1.0]
\begin{axis}[ ymin=0, xlabel = variáveis aleatórias, ylabel = frequência]

\addplot [
    domain=0:10, 
    samples=100, 
    color=red]
    {exp(-x)};
\end{axis}
\end{tikzpicture}
\caption{Some figure}
\end{figure}

Best Answer

As Sigur points out, the caption is centered w.r.t. the full tikzpicture, not just the plot, but the plot with labels. If you really don't want this, you might mess around with the bounding box.

\documentclass{article}
\usepackage{float}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepackage{lipsum}
\begin{document}
\lipsum[1]
\begin{figure}[H]
\centering
\begin{tikzpicture}[scale=1.0]
\begin{pgfinterruptboundingbox}
\begin{axis}[ ymin=0, xlabel = variáveis aleatórias, ylabel = frequência]

\addplot [
    domain=0:10, 
    samples=100, 
    color=red]
    {exp(-x)};
\end{axis}
\end{pgfinterruptboundingbox}
\path[use as bounding box] ([yshift=-8mm]current axis.south west) rectangle (current axis.north east);
\end{tikzpicture}
\caption{Some figure}
\end{figure}
\lipsum[2]
\end{document}

enter image description here

Other options include shifting the caption to the left, or, what might be more elegant, to add the same space to the bounding box on the right.

\documentclass{article}
\usepackage{float}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usetikzlibrary{calc}
\usepackage{lipsum}
\begin{document}
\lipsum[1]
\begin{figure}[H]
\centering
\begin{tikzpicture}[scale=1.0]
\begin{axis}[ ymin=0, xlabel = variáveis aleatórias, ylabel = frequência,ylabel style={alias=ylab}]

\addplot [
    domain=0:10, 
    samples=100, 
    color=red]
    {exp(-x)};
\end{axis}
\path let \p1=($(current axis.west)-(ylab.north)$) in (current axis.east) -- ++(\x1,0);
axis.north east);
\end{tikzpicture}
\caption{Some figure}
\end{figure}
\lipsum[2]
\end{document}

enter image description here

This saves you from having to add an yshift by hand.