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

5

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}
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.