212k views
4 votes
Implement a function with signature barGraph(w, h, data) which creates and returns a cs1graphics.Canvas instance that has width w and height h and which visualizes the given data as a bar graph. The data will be a nonempty list of positive integers. (You do not need to error-check the parameters.) Your visualization must have rectanglar bars with equal width that collectively use 80% of the width of the canvas (leaving 10% padding on left and right) and the bars should be vertically aligned at their bottom edge such that the maximum value in the data results in a bar that uses 80% of the height of the canvas (leaving 10% padding at top and bottom). As an example, the call barGraph (400, 300, [5, 8, 2, 7]) should produce the following image: from cs1graphics import * def barGraph(w, h, data): pass

1 Answer

4 votes

Answer:

def barGraph(w, h, data):

# creating Canvas

paper = Canvas(w, h)

# defining variables

largest = max(data) # largest element in data

length = len(data) # length of data list

barWidth = 0.8 * w / length # length of each bar of the histogram

maxBarHeight = 0.8 * h # maximum height of each bar of the histogram

minBarHeight = maxBarHeight / largest # minimum height of each bar

# Starting points

x = 0.1 * w

y = 0.9 * h

# looping through the list

for i in data:

currBarHeight = minBarHeight * i # current bar height

x1 = x + barWidth

y1 = y - currBarHeight

# creating the rectangle, and adding it to the bar graph

bar = Polygon( Point(x,y), Point(x,y1), Point(x1,y1), Point(x1,y) )

bar.setFillColor('grey')

paper.add(bar)

x = x1

# returning the canvas

return paper

User Sanyi
by
7.2k points