4

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.

3 Answers 3

8

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

A \pic could be useful here.

Something like this:

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

\tikzset
{%
  pics/my rectangle/.style n args={3}{% width, height, filling percentage
    code={%
      \fill (0,0) rectangle (#1,0.01*#2*#3);
      \draw (0,0) rectangle (#1,#2);
    }},
}

\begin{document}
\begin{tikzpicture}
  \pic[draw=red,fill=orange]  at (0,0) {my rectangle={2}{3}{25}};
  \pic[draw=black,fill=green] at (3,0) {my rectangle={3}{2}{75}};
\end{tikzpicture}
\end{document}

enter image description here

4

Without any minimal example, it is difficult to know how you want it implemented!? Here is one way:

\documentclass[tikz,border=1 cm]{standalone}
\begin{document}
\begin{tikzpicture}
\newcommand{\height}{4 cm}
\fill[red] (0,0) rectangle  +(5,0.58*\height);
\fill[green] (0,0) rectangle  +(5,0.22*\height);
\draw (0,0) rectangle  +(5,\height);
\end{tikzpicture}
\end{document}

Filled rectangle

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .