At My Fingertips

Bar Chart

Let's implement a function that turns a list of numbers into a bar chart.

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

bar_chart([0.5, 1.0, 0.9, 1.0, 1.5, 0.1], 200, 100)

bar chart

A Single Bar

A bar chart consists of bars that are placed next to each other. To determine the height of a bar, we need to take into account:

  • the amount of space we have for the complete chart (specifically, the chart_height)
  • the value represented by this specific bar (value)
  • the maximum value to be shown in the chart (max_value), which will be represented by the tallest bar, which will take up the entire chart_height

Compute the bar_height, and then construct a rectangle with the necessary dimensions and red color.

Loading...

A Gap

We will want gaps between bars. To construct a gap of a specific width, we can create a rectangle with that width and with a height of 0. While we have to specify the color of the rectangle, the color we pick does not really matter, because the rectangle has 0 height and thus is invisible.

Loading...

Let's "show" the gap by creating two 60-width bars separated by a 10-width gap:

Loading...

Do you see how they are separated? That's our gap!

Also, do you realize that they are vertically centered? We don't want that for our bar chart: we will want the bars to be bottom-aligned. Thus, we won't use beside to compose them.

A Complete Bar Chart

Given the bar and gap functions, we are now ready to create a complete bar chart.

Our bar_chart function receives a list of values, and the desired overall width and height of the chart. Given this information, compute:

  • max_value - the maximum of the given values
  • bar_count - the number of bars
  • gap_count - the number of gaps between bars
  • bar_width - the width of one bar (given width, bar_count, gap_count, and gap_width_fraction)
  • gap_width - given bar_width and gap_width_fraction

Given all this information, implement a loop that uses bar, gap, empty_graphic, compose, and pin to combine the necessary bars and gaps. Make sure that the gaps only exist between bars (the bars extend all the way to the left and right edge of the chart).

Loading...

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

Bar 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 b744b47 (Tue, 08 Oct 2024 16:30:14 GMT)