[Tex/LaTex] Exact scaling with TiKZ-scale

pgfplotstikz-pgftikzscale

I am using tikzscale to scale all my figures to the same size. This works quite nicely, but sometimes there is a difference in the scaled width. I can manually tweak the scale parameter (using pdfcrop and looking at the resulting page width), but it would be easier if the size would be exact right out of tikzscale.

In this example the width of the first plot seems a bit too narrow in comparison with the box while the second plot seems too be the widest figure.

enter image description here

MWE

\documentclass{article}

\usepackage{filecontents}

\usepackage{tikz, tikzscale, pgfplots}
\usetikzlibrary{calc}

\begin{document}

\begin{filecontents}{fig.tikz}
\begin{tikzpicture}
\begin{axis}[]
\addplot {x^2};
\end{axis}
\end{tikzpicture}
\end{filecontents}

\begin{filecontents}{fig2.tikz}
\begin{tikzpicture}
\draw (0,0) rectangle (1,0.2);
\end{tikzpicture}
\end{filecontents}

\begin{filecontents}{fig3.tikz}
\begin{tikzpicture}
\begin{axis}[yticklabel style={overlay}]
\addplot {x^2};
\end{axis}
\end{tikzpicture}
\end{filecontents}


\includegraphics[width=1.00\linewidth, axisratio=4]{fig.tikz} 

\vspace{0.1cm}

\includegraphics[width=1.00\linewidth]{fig2.tikz} 

\vspace{0.1cm}

\includegraphics[width=1.00\linewidth, axisratio=4]{fig3.tikz} 


\end{document}

Best Answer

tikzscale correctly scales both axes to the entire text width. However, the tick labels have white space around them, which is taken into account for the scaling.

You can remove the white space around the tick labels by setting

\pgfplotsset{
    xticklabel style={
        inner xsep=0pt
    },
    yticklabel style={
        inner xsep=0pt,
        xshift=-0.333em
    }
}

(note the xshift for the y tick labels, because they used the inner xsep for their positioning)

\documentclass{article}

\usepackage{filecontents}

\usepackage{tikz, tikzscale, pgfplots}
\usetikzlibrary{calc}

\begin{document}

\pgfplotsset{
    xticklabel style={
        inner xsep=0pt
    },
    yticklabel style={
        inner xsep=0pt,
        xshift=-0.333em
    }
}

\begin{filecontents}{fig.tikz}
\begin{tikzpicture}
\begin{axis}[]
\addplot {x^2};
\end{axis}
\end{tikzpicture}
\end{filecontents}

\begin{filecontents}{fig2.tikz}
\begin{tikzpicture}[remember picture]
\draw (0,0) coordinate (A) rectangle (1,0.2) coordinate (B);
\end{tikzpicture}
\end{filecontents}

\begin{filecontents}{fig3.tikz}
\begin{tikzpicture}
\begin{axis}[yticklabel style={overlay}]
\addplot {x^2};
\end{axis}
\end{tikzpicture}
\end{filecontents}


\includegraphics[width=1.00\linewidth, axisratio=4]{fig.tikz} 

\vspace{0.1cm}

\includegraphics[width=1.00\linewidth]{fig2.tikz} 

\vspace{0.1cm}

\includegraphics[width=1.00\linewidth, axisratio=4]{fig3.tikz} 

\tikz[remember picture, overlay, red] \draw (A) -- +(0,6cm) -- +(0,-4cm)
(B) -- +(0,4cm) -- +(0,-6cm);
\end{document}