Draw a Bar Graph (Python)

Please support our Python advertiser: Programming Forums
Nov 1st, 2006
Views: 8,155
AddThis Social Bookmark Button
This shows you how to draw a colorful bar graph of a data set using the Tkinter canvas and rectangles. An attempt has been made to use most of the canvas area for the graph. The bars are spaced and labeled with the corresponding value. The x-axis is simply the index of the data set.
Last edited : Dec 23rd, 2006.
python Syntax
  1. # drawing a bar graph with the Tkinter canvas and
  2. # canvas.create_rectangle(x0, y0, x1, y1, option, ...)
  3. # note: coordinates are relative to the top left corner of the canvas
  4. # used a more modern import to give Tkinter items a namespace
  5. # tested with Python24 by vegaseat 01nov2006
  6.  
  7. import Tkinter as tk # gives tk namespace
  8.  
  9. data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]
  10.  
  11. root = tk.Tk()
  12. root.title("Tkinter Bar Graph")
  13. c_width = 400
  14. c_height = 350
  15. c = tk.Canvas(root, width=c_width, height=c_height, bg= 'white')
  16. c.pack()
  17.  
  18. # the variables below size the bar graph
  19. # experiment with them to fit your needs
  20. # highest y = max_data_value * y_stretch
  21. y_stretch = 15
  22. # gap between lower canvas edge and x axis
  23. y_gap = 20
  24. # stretch enough to get all data items in
  25. x_stretch = 10
  26. x_width = 20
  27. # gap between left canvas edge and y axis
  28. x_gap = 20
  29.  
  30.  
  31. for x, y in enumerate(data):
  32. # calculate reactangle coordinates (integers) for each bar
  33. x0 = x * x_stretch + x * x_width + x_gap
  34. y0 = c_height - (y * y_stretch + y_gap)
  35. x1 = x * x_stretch + x * x_width + x_width + x_gap
  36. y1 = c_height - y_gap
  37. # draw the bar
  38. c.create_rectangle(x0, y0, x1, y1, fill="red")
  39. # put the y value above each bar
  40. c.create_text(x0+2, y0, anchor=tk.SW, text=str(y))
  41.  
  42. root.mainloop()

Only community members can submit or comment on code snippets. You must register or log in to contribute.

Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 12:47 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC