Day 28 - Bar Chart Using Turtle and Nested Functions, Part 2

Part two of our bar chart - We will create functions to vertically and horizontally resize the chart to automatically fit based on the number and size of the values.

Starter Code

from turtle import *

intSpace = 20

scr = Screen()
print(window_width()/2, window_height()/2)


teleport(-300,-300)


def drawBar(intHeight, intWidth, strColor):
    setheading(90)
    tupStart = (xcor(),ycor())
    color(strColor)
    begin_fill()
    forward(intHeight)
    right(90)
    forward(intWidth)
    right(90)
    forward(intHeight)
    right(90)
    forward(intWidth)
    right(90)
    end_fill()
    teleport(xcor()+(intWidth//2),ycor()-20)
    write(intHeight, align='center', font=('Arial',12,'bold'))
    teleport(tupStart[0]+intWidth+intSpace,tupStart[1])

drawBar(200,20,"red")
drawBar(300,20,"blue")


done()

Finished Code

from turtle import *

intSpace = 15
intWidth = 100
intMargin = 35
liColors= ["red", "blue", "green", "pink", "orange", "purple", "light blue", "dark red", "turquoise", "chartreuse", "dark blue", "dark magenta", "pale violet red"]
liData = [500,30000,300]


scr = Screen()
print(window_width()/2, window_height()/2)

def adjHeight(liData, intOGH):
    intMax = max(liData)
    intHeight = int(intOGH/intMax * 725)
    return intHeight

def getBarWidth(liData, intMargins, intSpace):
    intBars = len(liData)
    intTotSpace = (intMargins * 2) + (intSpace*(intBars-1))
    intBarWidth = (window_width() - intTotSpace) // intBars
    return intBarWidth


def drawBar(intHeight, intWidth, strColor):
    setheading(90)
    tupStart = (xcor(),ycor())
    color(strColor)
    begin_fill()
    forward(adjHeight(liData,intHeight))
    right(90)
    forward(intWidth)
    right(90)
    forward(adjHeight(liData,intHeight))
    right(90)
    forward(intWidth)
    right(90)
    end_fill()
    teleport(xcor()+(intWidth//2),ycor()-20)
    write(intHeight, align='center', font=('Arial',12,'bold'))
    teleport(tupStart[0]+intWidth+intSpace,tupStart[1])

def drawChart(liData):
    teleport((window_width()/2*(-1)+intMargin), -330)

    intWidth = getBarWidth(liData, intMargin, intSpace)

    intNumBars = len(liData)

    intIndex = 0

    for intBar in liData:
        drawBar(intBar, intWidth, liColors[intIndex])
        intIndex += 1


drawChart(liData)
hideturtle()
done()