Waffle Chart
Everyone knows that pie charts are overused. This example shows how to quickly build the waffle chart.
First, let's import the necessary components.
Then we also need some data (sorted).
We define the square size, gutter, and how many squares we want to have on every side. Usually, we want to show the share in %, therefore a reasonable choice is to have a 10 by 10 chart. We also need to know the sum of values from the given dataset.
Next, we have to calculate how many cells each group should fill.
Now we have to compute the cell size, ensuring gutters on both sides.
Create a list that maps each square index to a group (color).
If there's any discrepancy, fill the rest with a default group (optional).
Create a separate path for each group.
Loop over all squares using index-based placement. You can determine the row and column index using modulo and floor division (lines 19-20). Remember to only draw if the cell belongs to a group (not left as None; see lines 25-27).
Create an SVG element with the specified dimensions.
And finally, append each group's path element to the SVG.
That's it. If you are using Jupyter Notebook, you can render your chart using svg.display()
. Alternatively, save your chart to a file.