[Tex/LaTex] Scaling a tikzpicture for a Beamer slide


I have the following Beamer slide:



\tikzstyle{decision} = [diamond, draw, fill=blue!20, text width=4.5em, text badly centered, node distance=3cm, inner sep=0pt]
\tikzstyle{block} = [rectangle, draw, fill=blue!20, text width=5em, text centered, rounded corners, minimum height=4em]
\tikzstyle{line} = [draw, -latex    ]
\tikzstyle{cloud} = [draw, ellipse,fill=red!20, node distance=3cm, minimum height=2em]


\begin{frame}{Simulated Annealing (SA)}
        \begin{tikzpicture}[node distance = 2cm, auto]
            \node[block]                  (init){Init $n=0$, $T_0$, and $S_0$};
            \node[block, below of=init]   (nbrh){$S_{n+1}=N(S_n)$};
            \node[decision, below of=nbrh](ovgt){$f(S_{n+1}) \le f(S_n)$};
            \node[block, below of=ovgt]   (accp){Accept $S_{n+1}$};
            \node[decision, right of=ovgt](rand){$e^{-\frac{\Delta f}{t_n}}$};
            \node[block, right of=nbrh]   (rejj){Reject $S_{n+1}$};
            \node[block, below of=accp]   (incr){$T_{n+1} = K(T_n)$ and $n++$};
            \node[block, below of=incr]   (stop){Stop};
            \node[decision, left of=stop] (stcd){Stop?};

            \path[line] (init) --          (nbrh);
            \path[line] (nbrh) --          (ovgt);
            \path[line] (ovgt) -- node{yes}(accp);
            \path[line] (ovgt) -- node{no} (rand);
            \path[line] (rand) -- node{no} (rejj);
            \path[line] (rejj) --          (nbrh);
            \path[line] (rand) |- node{yes}(accp);
            \path[line] (accp) -|          (stcd);
            \path[line] (stcd) -- node{yes}(stop);
            \path[line] (stcd) |- node{no} (nbrh);


and I got the code mostly from here.

The only problem is that it doesn't fit in the beamer slide. It isn't auto scaled, and it runs way off the bottom.

I have tried adding scale = 0.25 to the \begin{tikzpicture}[] but that didn't do anything at all.

Is there any way to auto-fit the whole tikzpicture into the available space in my frame?

enter image description here

Bonus question: Why is Reject S_{n+1} not horizontally aligned with the exponential decision underneath, and as such – why is the arrow connecting them at an angle? (i.e., how is this fixed?)

Best Answer

Using scale = 0.25 to the \begin{tikzpicture}[] only scales coordinates, but not node sizes. For complex things like tikzpictures I recommend my adjustbox package. Here you can specify the maximal size, e.g. in factors of the text width and height. Note that the text height also includes the head line. You can add the center key to horizontally center it without adding vertical space before and after like with the center environment:

% Preamble:

% Body:

\begin{adjustbox}{max totalsize={.9\textwidth}{.7\textheight},center}

See the adjustbox manual for more keys and other details.