简体   繁体   中英

Turtle module in Python:

Here is the question : Write a non-fruitful function called barChart, that takes the numeric list of data as a parameter, and draws the bar chart. Write a full program calling this function. The current version of the drawBar function unfortuately draws the top of the bar through the bottom of the label. A nice elaboration is to make the label appear completely above the top line. To keep the spacing consistent you might pass an extra parameter to drawBar for the distance to move up. For the barChart function make that parameter be some small fraction of maxheight+border. The fill action makes this modification particularly tricky: You will want to move past the top of the bar and write b efore or after drawing and filling the bar..

What should I change?

Here is my code :

import turtle

def drawBar(t, height):
""" Get turtle t to draw one bar, of height. """
t.begin_fill()               # start filling this shape
t.left(90)
t.forward(height)
t.write(str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill()                 # stop filling this shape

You can pass the maximum value of the number list then draw the text and bar separately.

Try this code:

import turtle

def drawBar(t, height, mx):
    # draw text
    t.penup()
    t.left(90)
    t.forward(mx*10+10)
    t.write(str(height).center(12))
    t.right(180)
    t.forward(mx*10+10)
    t.left(90)
    t.pendown()
    
    """ Get turtle t to draw one bar, of height. """
    t.fillcolor(.1, 1-1*height/mx/2, .1)  # darker is higher value
    t.begin_fill()       # start filling this shape
    t.left(90)
    t.forward(height*10)
    #t.write("  " + str(height))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height*10)
    t.left(90)
    t.end_fill() 
    
    # bottom line
    t.right(180)
    t.forward(40)
    t.right(180)
    t.forward(40)
    
t = turtle.Turtle()

nums = [3,1,4,1,5,9,2]

t.speed(0) # fastest
for n in nums:
   drawBar(t, n, max(nums))
t.hideturtle()

input('Enter to exit')

Output

图表

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM