# Tikzpicture with caption

How I do a caption in Tikz? e.g.

\begin{tikzpicture}
\draw (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);
\end{tikzpicture}

is an error.

A caption is a thing you attach to a figure; a tikzpicture is like an image, or a block of text, or whatever you want to put into a picture.

Try:

\begin{figure}
\begin{tikzpicture}
\draw (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);
\end{tikzpicture}
\end{figure}
• Okay thanks but, does it work in class article and book? – pga11 Mar 30 at 19:46
• ...have you tried? ;-) – Rmano Mar 30 at 19:47
• @luis.pga please prepare a minimal working example (MWE) that shows the errors and post it, better if in another question. The problem in posting snippets, as you did, is that it's impossible to know what packages and options you have --- my cristall ball is broken and I can go out to repair it... ;-) – Rmano Mar 30 at 20:35
• @luis.pga I can reproduce your errors if I wrap the above code into $...$. The above answer is correct, wrapping the code in a math environment is not. – Schrödinger's cat Mar 30 at 21:32
• Okay guys, forget it, I had an error in my code, your solution is correct, Thanks and sorry for bothering you.! – pga11 Mar 30 at 21:42

To be clear, Rmano's answer is the way to go in almost all realistic cases. However, exceptionally there can be good reasons to just add a caption to some tikzpicture, e.g. when you arrange them in a tabular. In this case you can do

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\tikzset{caption/.style={insert path={
let \p1=($(current bounding box.east)-(current bounding box.west)$) in
(current bounding box.south) node[below,text width=\x1-4pt,align=center]
{\captionof{figure}{#1}}}}}
\usepackage{caption}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- (4,0) -- (4,4) -- (0,4) -- (0,0);
\end{tikzpicture}
\end{document}

Or you can define a style that automatically puts the caption at the end of the tikzpicture.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\tikzset{caption/.style={execute at end picture={\path
let \p1=($(current bounding box.east)-(current bounding box.west)$) in
(current bounding box.south) node[below,text width=\x1-4pt,align=center]
{\captionof{figure}{#1}};}}}
\usepackage{caption}
\begin{document}