TransWikia.com

Align rectangle with text in Tikz

TeX - LaTeX Asked by user213544 on August 28, 2021

I am creating the legend of a figure in Tikz, and would like to align two rectangles with text:

  node(legend) at (1.7,-6.75) {Legend: }; 
    node[right=0.5cm of legend] (myNode) {};
      draw[](myNode) rectangle +(0.4,0.2);
    node[right=1.5cm of legend] (myNode) {};
      draw[](myNode) rectangle +(0.4,0.2);

enter image description here

I am able to draw the rectangles, but they seem to be aligned with their bottom left corner to the center of the ‘legend’ node. How do I align the center of the rectangles to the center of the ‘legend’ node?

One Answer

Instead of drawing a rectangle after specifying its location using a node, the node itself is a rectangle by default. Just add the key draw to the node and specify the width and height. The reason why your rectangles are not vertically centered is that rectangles start drawing from corner adding two lengths to reach the opposite corner.

documentclass[12pt,a4paper]{article}
usepackage{tikz}
usetikzlibrary{positioning}
begin{document}

begin{tikzpicture}[rect/.style={draw,minimum width=0.4cm,minimum height=0.2cm}]
node (legend) at (1.7,-6.75) {Legend:}; 
node [right=0.5cm of legend,rect](myNode1){};
node [right=1.5cm of legend,rect](myNode2){};
end{tikzpicture}

end{document}

enter image description here

Correct answer by AboAmmar on August 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP