4

How can I add a node on top of a rectangle path ?

\path[draw] (upperleft) rectangle (lowerright) node[???] {Top};

I am aware of the midway parameter that I can use, but this locates my Top label on the middle of the rectangle and not at top

jub0bs
  • 58,916
Manuel Selva
  • 1,839
  • 1
    See if http://tex.stackexchange.com/questions/47704/how-to-establish-node-anchor-like-points-on-a-tikz-rectangle-path-is-there-a?rq=1 solves your problem. Or you could maybe use (this is untested) \path (lowerright |- upperleft) -- (upperleft) node[midway] {top};. – Torbjørn T. Aug 07 '14 at 06:34

2 Answers2

6

One possibility, although not very TikZ-idiomatic, is to combine your \path command with Torbjørn's suggestion into a macro:

enter image description here

\documentclass{article}

\usepackage{tikz}

\newcommand\namedrectangle[3][]{%
  \path[draw] (#2) rectangle (#3);
  \path (#3 |- #2) -- (#2) node[midway,above] {#1};
}

\begin{document}

\begin{tikzpicture}
\coordinate (upperleft) at (0,1);
\coordinate (lowerright) at (2,0);
\namedrectangle[Named rectangle]{upperleft}{lowerright}
\end{tikzpicture}

\end{document}
jub0bs
  • 58,916
4

Another option. If you know corners coordinates use fit library to draw the rectangle while the text is added with label. You can use named coordinates or just numerical ones. In this last case include coordinates list inside brackets.

\documentclass[tikz,border=2mm]{standalone}

\usetikzlibrary{fit}

\begin{document}

\begin{tikzpicture}
\fill[red] (0,1) circle[radius=1pt] coordinate (upperleft);
\fill[red]  (2,0) circle[radius=1pt] coordinate (lowerright);
\node[draw, fit=(upperleft) (lowerright), inner sep=0pt, label={Named rectangle}] (rectangle) {};

\node[draw, fit={(3,0) (5,1.4)}, inner sep=0pt, label={[text width=2cm, align=center]Another named rectangle}
] (rectangle-b) {};

\end{tikzpicture}

\end{document}

enter image description here

Ignasi
  • 136,588