At My Fingertips
Rapid Playground
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)
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:
chart_height
)value
)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.
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.
Let's "show" the gap by creating two 60-width bars separated by a 10-width gap:
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.
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 valuesbar_count
- the number of barsgap_count
- the number of gaps between barsbar_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).
This activity has been created by LuCE Research Lab and is licensed under CC BY-SA 4.0.
Bar Chart
PyTamaro is a project created by the Lugano Computing Education Research Lab at the Software Institute of USI
Privacy Policy • Platform Version c08406b (Wed, 20 Nov 2024 12:30:00 GMT)