[Tex/LaTex] Scale tikz figure to a percentage of \textwidth

graphicsmarginsscalingtikz-pgf

A user asked a question about scaling a figure to a factor of \textwidth and got an answer like this:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
  \includegraphics[width=0.5\textwidth]{file}
\end{document}

however, I'm not sure how to apply this to my document:

\documentclass{article}
\usepackage{graphicx}
\usepackage{tikz}
\begin{document}
  \begin{figure}[!h]
    \centering
    \begin{tikzpicture}
      %
    \end{tikzpicture}
    \caption{This figure has a width which is a factor of \\textwidt}
  \end{figure}
\end{document}

I've tried

\begin{figure}[!h, width=\textwidth]

but that didn't work.

Best Answer

You need tikzscale package. Save the contents

\begin{tikzpicture}
  \draw (0,0) circle (2cm);
  \node at (0,0) {Me};
\end{tikzpicture}

as myfig.tikz (say) and use \includegraphics

Code:

\documentclass{article}
\usepackage{tikz}
\usepackage{tikzscale}
\usepackage{filecontents}    %% only for this demo
\begin{filecontents*}{myfig.tikz}
  \begin{tikzpicture}
      \draw (0,0) circle (2cm);
      \node at (0,0) {Me};
  \end{tikzpicture}
\end{filecontents*}
\begin{document}
  \begin{figure}[htb]
    \centering
    \includegraphics[width=0.5\textwidth]{myfig.tikz}
    \caption{This figure has a width which is a factor of text width}
  \end{figure}

  \begin{figure}[htb]
    \centering
    \includegraphics[width=0.2\textwidth]{myfig.tikz}
    \caption{This figure has a width which is a factor of text width}
  \end{figure}
\end{document}

enter image description here

Unlike \resizebox, the fonts are not scaled in-appropriately. If you want to scale fonts too, use \begin{tikzpicture}[transform shape] instead of \begin{tikzpicture}.

With \resizebox from graphicx:

\documentclass{article}
\usepackage{tikz}

\begin{document}
  \begin{figure}[htb]
    \centering
    \resizebox{0.5\textwidth}{!}{%
    \begin{tikzpicture}
      \draw (0,0) circle (2cm);
      \node at (0,0) {Me};
  \end{tikzpicture}
    }%
    \caption{This figure has a width which is a factor of text width}
  \end{figure}

  \begin{figure}[htb]
    \centering
    \resizebox{0.2\textwidth}{!}{%
    \begin{tikzpicture}
      \draw (0,0) circle (2cm);
      \node at (0,0) {Me};
  \end{tikzpicture}
    }%
    \caption{This figure has a width which is a factor of text width}
  \end{figure}
\end{document}

enter image description here