Model answer explanation of a Canvas Bar Chart program in Python
<p>In CS class we had an exercise where we had to construct a bar chart using Canvas in Python 2.7.2. Below is the model solution on how it should be done, it would be greatly appreciated if someone could explain how the program is written and what each line/aspect of the program means. Please could you answer to the extent to which you can be bothered.</p>

<p>Thanks in advance:</p>

<p>This is function.py on which the bar chart program is based.</p>

<pre><code>def maxList(numbers):
maximum = numbers[0]

for number in range(1, len(numbers)):

    if numbers[number] &gt; maximum:

        maximum = numbers[number]

return maximum
</code></pre>

<p>This is the bar chart program itself.</p>

<pre><code>from function import *
from Canvas import *
from random import *

def barchart(xOrigin, yOrigin, xSize, ySize, labels, data):

set_size(xSize + (2 * xOrigin), ySize + (2 * (yOrigin - ySize)))

items = len(data)

barWidth = xSize / items

largeData = maxList(data)

yScale = ySize / float(largeData)


create_line(xOrigin, yOrigin, xOrigin + xSize, yOrigin)
create_line(xOrigin, yOrigin, xOrigin, yOrigin - ySize)


yGrad = 0
while abs(yGrad) &lt;= ySize:

    create_line(xOrigin - 5, yOrigin + yGrad, xOrigin, yOrigin + yGrad)
    yGrad -= yScale

create_text(xOrigin - 15, yOrigin, text = "0")
create_text(xOrigin - 15, yOrigin - ySize, text = str(largeData))

labelX = xOrigin + (barWidth / 2)


for label in labels:
     create_text(labelX, yOrigin + 15, text = label)
     labelX += barWidth


barX = xOrigin + 2
barNum = 1
barColour = ["black", "white", "red", "blue", "green", "yellow", "cyan", "magenta"]


for datum in data:
    if datum != 0:
        create_rectangle( barX, yOrigin, barX + barWidth - 2, yOrigin - (datum * yScale), fill = barColour[barNum % (len(barColour)) - 1])
    barX += barWidth
    barNum += 1

complete()

labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

data = []

for i in labels:
  data += [randint(0, 100)]


barchart(50,550,500,500, labels, data)
</code></pre>
