Jim
Jim

Reputation: 151

Use tkinter to draw a specific bar chart

enter image description here

I am trying to figure out the easiest way to do the bat chart above. I'm learning tkinter and I know that I can use Canvas, Frame and Label to do it, but it seems to have too much redundancy.

Upvotes: 3

Views: 12064

Answers (2)

Koga
Koga

Reputation: 525

Some googling revealed this link to me.

I have included the example code given there and I have hopefully commented it enough so you can understand what is going on.

I am slightly unsure about the accuracy of my for-loop description, so please comment if anything is wrong.

import tkinter as tk


# Define the data points
data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]

root = tk.Tk()
root.title("Bar Graph")

c_width = 400  # Define it's width
c_height = 350  # Define it's height
c = tk.Canvas(root, width=c_width, height=c_height, bg='white')
c.pack()

# The variables below size the bar graph
y_stretch = 15  # The highest y = max_data_value * y_stretch
y_gap = 20  # The gap between lower canvas edge and x axis
x_stretch = 10  # Stretch x wide enough to fit the variables
x_width = 20  # The width of the x-axis
x_gap = 20  # The gap between left canvas edge and y axis

# A quick for loop to calculate the rectangle
for x, y in enumerate(data):

    # coordinates of each bar

    # Bottom left coordinate
    x0 = x * x_stretch + x * x_width + x_gap

    # Top left coordinates
    y0 = c_height - (y * y_stretch + y_gap)

    # Bottom right coordinates
    x1 = x * x_stretch + x * x_width + x_width + x_gap

    # Top right coordinates
    y1 = c_height - y_gap

    # Draw the bar
    c.create_rectangle(x0, y0, x1, y1, fill="red")

    # Put the y value above the bar
    c.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y))

root.mainloop()

Upvotes: 4

Jim
Jim

Reputation: 151

At the end this the simple code I wrote, which may be a little bit redundant and not very flexible.

from tkinter import *


root = Tk()
root.title("Bar Graph")

c_width = 500
c_height = 200
c = Canvas(root, width=c_width, height=c_height)
c.pack()

c.create_rectangle(20, 140, 120, 180, fill="red")
c.create_text(70, 130, text="Projects--20%")
c.create_rectangle(140, 160, 240, 180, fill="blue")
c.create_text(190, 150, text="Quizzes--10%")
c.create_rectangle(260, 120, 360, 180, fill="green")
c.create_text(310, 110, text="Midterm--30%")
c.create_rectangle(380, 100, 480, 180, fill="orange")
c.create_text(430, 90, text="Final--40%")
c.create_line(0, 180, 500, 180)

root.mainloop()

Upvotes: 1

Related Questions