How to Create a 3D Bar Chart In Python Tkinter
In this Python tutorial we will create a 3D bar char using the Tkinter library for the graphical user interface.
Each bar features a distinct front, top, and side face, creating a three-dimensional appearance.
What We Are Gonna Use In This Project:
- Python Programming Language.- Tkinter for GUI.
- VS Code Editor.
- VS Code Editor.
Project Source Code:
import tkinter as tk
import random
class ThreeDBarChartPanel(tk.Canvas):
def __init__(self, master=None, **kwargs):
# Initialize the ThreeDBarChartPanel as a Canvas
super().__init__(master, **kwargs)
# Bar Colors
self.color_side_face = "#2c3e50"
self.color_top_face = "#e74c3c"
self.color_front_face = "#3498db"
# Draw the 3D bar chart
self.draw_chart()
def draw_chart(self):
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
num_bars = 10
bar_width = 40
bar_spacing = 30
base_x = (width - (num_bars * (bar_width + bar_spacing) - bar_spacing)) /2
base_y = height - 100
labels = [f"label{i}" for i in range(1, num_bars + 1)]
# Draw horizontal lines for reference
num_horizontal_lines = 5
horizontal_spacing = (base_y - 50) // num_horizontal_lines
for i in range(num_horizontal_lines + 1):
y = base_y - i * horizontal_spacing
#self.create_line(30, y, width - 20, y, fill="lightgray", dash=(2,2))
self.create_line(30, y, width - 20, y, fill="lightgray")
# Draw Bars
for i in range(num_bars):
x = base_x + i * (bar_width + bar_spacing)
bar_height = random.randint(50, 250)
z = 10
# Draw the front face of the bar
self.create_rectangle(x, base_y - bar_height, x + bar_width, base_y,
fill=self.color_front_face)
# Draw the top face of the bar
top_face = [ x, base_y - bar_height, x + bar_width, base_y-bar_height,
x + bar_width + z, base_y - bar_height-z, x + z, base_y - bar_height-z ]
self.create_polygon(top_face, fill=self.color_top_face)
# Draw the side face of the bar
side_face = [ x + bar_width, base_y - bar_height, x + bar_width, base_y,
x + bar_width + z, base_y - z, x + bar_width + z, base_y - bar_height-z ]
self.create_polygon(side_face, fill=self.color_side_face)
# Draw vertical axis labels
axis_label_x = x + bar_width / 2
axis_label_y = base_y + 20
self.create_text(axis_label_x, axis_label_y, text=labels[i])
# Draw horizontal axis labels
num_ticks = 5
tick_spacing = (base_y - 50) / num_ticks
self.create_text(base_x - 20, base_y - 5, text="0")
for i in range(1, num_ticks + 1):
tick_value = 40 + i * 40
self.create_text(base_x - 30, base_y - i * tick_spacing,
text = str(tick_value))
class ThreeDBarChartApp:
def __init__(self, root):
self.root = root
self.root.title("3D Bar Chart")
self.root.geometry("800x500")
self.root.resizable(False, False)
# Create and pack the ThreeDBarChartPanel
self.chartPanel = ThreeDBarChartPanel(self.root, bg="white", width="800",
height="400")
self.chartPanel.pack(expand=True, fill="both")
if __name__ == "__main__":
root = tk.Tk()
app = ThreeDBarChartApp(root)
root.mainloop()