在Python中模拟Canvas条形图程序的答案解释

时间:2012-01-22 23:00:43

标签: python

在CS课程中,我们进行了练习,我们必须使用Python 2.7.2中的Canvas构建条形图。下面是关于如何完成的模型解决方案,如果有人能够解释程序的编写方式以及程序的每个方面/方面的含义,将不胜感激。请你回答一下你可以打扰的程度。

提前致谢:

这是条形图程序所基于的function.py。

def maxList(numbers):
maximum = numbers[0]

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

    if numbers[number] > maximum:

        maximum = numbers[number]

return maximum

这是条形图程序本身。

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) <= 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)

0 个答案:

没有答案