At My Fingertips

Documentation

Simple Pie Chart

A pie chart represents numerical proportions as slices of a pie. The size of a slice is proportional to the quantity it represents. Each slice usually has a different color.

NOTE: It is often better to use bar charts instead of pie charts, for example because comparing the sizes of two circular sectors in a pie chart can be more challenging than comparing the sizes of two bars in a bar chart.

Let's study this potential problem in a future activity. For now, let's implement a function to create simple pie charts!

Interface

Our function has the following signature:

def pie_chart(
  values: list[float], colors: list[Color], radius: float
) -> Graphic:

It takes the following parameters:

  • values -- the list of numerical values to plot
  • colors -- the list of colors to use for plotting each value
  • radius -- the radius of the pie chart

In the end, you should be able to call it like this:

show_graphic(pie_chart([1.0, 2.0, 3.0], [red, green, blue], 100))

This call should produce the following chart:

demo-chart-2.png

Decomposition

A pie chart is made up of slices, one slice per value. Each slice is a circular sector.

Implementation

You can use the circular_sector function to create a sector.

Check out the API (by hovering over the red word) to figure out where the pinning position of a circular sector is located. Use that fact for rotating and composing multiple circular sectors into a pie.

Loading...

Better Colors and More Slices

Now let's use your function for a slightly more complex pie chart. To be able to clearly distinguish the different pieces in a categorical visualizations (e.g., the different slices in a pie chart), picking a set of colors that are easily distinguishable is a good idea. The Color Brewer is a great resource to create such color palettes. Here we include a palette that is optimized for visualizing 10 different categories.

Note that in the code below, the number of values and the number of colors differ. Your pie_chart function should be able to deal with this situation. It should cycle through the given number of colors: If there are fewer values than colors, it should use the first N colors. If there are more values than colors, it should cycle through colors reusing the same color for multiple slices.

Loading...

What You Learned

You learned how to compose multiple circular sectors into a pie chart. You also learned about good color palettes for qualitative / categorical visualizations.


This activity has been created by LuCE Research Lab and is licensed under CC BY-SA 4.0.

Simple Pie Chart

Logo of PyTamaro

PyTamaro is a project created by the Lugano Computing Education Research Lab at the Software Institute of USI

Privacy PolicyPlatform Version 1cd5229 (Tue, 05 Nov 2024 16:55:57 GMT)