How can one partially fill a rectangle up to a certain relative height in TikZ

tikz-pgf

This answer How do we fill half rectangle in TikZ, shows how rectangles can be half-filled using the .south west and .east attributes of the path picture bounding box.

I would like to know how this generalizes to filling a rectangle up to a certain percentage of its total height.

I want to control the height of the color fill by using only the number corresponding to the relative height I'd like to fill (e.g., 22 %, 58 %). I do not want to achieve this relative fill height by manually figuring out the coordinates.

Best Answer

enter image description here

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand\partiallyFilledBox[1]{%
  \begin{tikzpicture}
    \coordinate (A) at (0,0);
    \coordinate (B) at (1,1);
    \draw[red,fill=red] (A) rectangle ($(A-|B)!#1!(B)$);
    \draw (A) rectangle (B);
  \end{tikzpicture}%
}
\begin{document}
\noindent
\partiallyFilledBox{0}
\partiallyFilledBox{0.1}
\partiallyFilledBox{0.2}
\partiallyFilledBox{0.3}
\partiallyFilledBox{0.4}
\partiallyFilledBox{0.5}
\partiallyFilledBox{0.6}
\partiallyFilledBox{0.7}\\
\partiallyFilledBox{0.8}
\partiallyFilledBox{0.9}
\partiallyFilledBox{1.0}
\partiallyFilledBox{1.1}
\partiallyFilledBox{1.2}
\partiallyFilledBox{1.3}
\partiallyFilledBox{1.4}
\partiallyFilledBox{1.5}
\end{document}
Related Question