Plotting, GUI and Databases
Plotting
Matplotlib is a Python library for data visualization. It helps you create charts, graphs, and plots to better understand and present data.
You can use it to draw:
-
Line charts
-
Bar charts
-
Pie charts
-
Scatter plots
-
Histograms
First, we have to import matplotlib.
import matplotlib.pyplot as plt
Here,
matplotlib→ main librarypyplot→ module that contains functions for creating plots
pyplot provides a state-based interface — it keeps track of the current figure and axes, so you can create and modify plots easily with simple function calls.Commonly Used
pyplot Functions:| Function | Description |
|---|---|
plt.plot() |
Draws line plots |
plt.scatter() |
Creates scatter plots |
plt.bar() |
Creates bar charts |
plt.hist() |
Plots histograms |
plt.pie() |
Creates pie charts |
plt.title() |
Adds a title to the plot |
plt.xlabel() / plt.ylabel() |
Labels axes |
plt.legend() |
Adds a legend |
plt.grid() |
Adds a grid |
plt.show() |
Displays the plot |
1️⃣ Line Chart
A Line Chart is used to display data points connected by straight lines.
It shows trends or changes over a period of time or a continuous variable.
It shows trends or changes over a period of time or a continuous variable.
Syntax:
plt.plot(x, y, color='blue', linestyle='-', marker='o', label='Line')
| Argument | Description |
|---|---|
x |
X-axis values |
y |
Y-axis values |
color |
Color of the line |
linestyle |
Style of the line ('-', '--', ':', '-.') |
marker |
Shape of points ('o', 's', '*', 'x') |
label |
Label for legend |
linewidth |
Thickness of line |
alpha |
Transparency level |
2️⃣ Bar Chart
A Bar Chart represents data with rectangular bars where the height (or length) of each bar shows the value of the variable.
It is used for comparing different categories.
It is used for comparing different categories.
Syntax:
plt.bar(x, height, color='orange', width=0.5, label='Data')
| Argument | Description |
|---|---|
x |
Categories or labels |
height |
Height of each bar |
color |
Color of bars |
width |
Thickness of bars |
label |
Label for legend |
align |
Align bars ('center' or 'edge') |
alpha |
Transparency of bars |
3️⃣ Pie Chart
A Pie Chart is a circular chart divided into slices, where each slice represents a portion or percentage of the total.
It’s used to show proportional data.
It’s used to show proportional data.
Syntax:
plt.pie(sizes, labels=names, colors=colors, autopct='%1.1f%%', startangle=90, shadow=True)
| Argument | Description |
|---|---|
sizes |
Values for each slice |
labels |
Names of slices |
colors |
List of colors for slices |
autopct |
Format for percentage labels |
startangle |
Rotation angle (in degrees) |
shadow |
Adds a shadow under the pie |
explode |
“Pull out” a slice for emphasis |
4️⃣ Scatter Plot
A Scatter Plot uses dots to represent the values of two variables.
It helps to identify relationships or correlations between them.
It helps to identify relationships or correlations between them.
Syntax:
plt.scatter(x, y, color='green', marker='x', s=80, alpha=0.7, label='Points')
| Argument | Description |
|---|---|
x |
X-axis values |
y |
Y-axis values |
color |
Color of points |
marker |
Shape of points ('o', 's', 'x', '*', etc.) |
s |
Size of points |
alpha |
Transparency |
label |
Label for legend |
5️⃣ Histogram
A Histogram displays the distribution of continuous data by grouping it into bins (ranges).
Each bar represents how many values fall into that range.
Syntax:
plt.hist(data, bins=5, color='purple', edgecolor='black', alpha=0.7)
| Argument | Description |
|---|---|
data |
Input numeric data |
bins |
Number of intervals/groups |
color |
Bar color |
edgecolor |
Border color of bars |
alpha |
Transparency |
orientation |
'vertical' or 'horizontal' |
rwidth |
Width of bars (0–1) |
Refer the below link for all plots:
- A grid is a set of horizontal and vertical lines drawn across the plot background to make reading values easier.
plt.grid(True)
- A legend is a box that explains what each line, color, or shape in your plot represents.
plt.legend()
Why Do We Use Matplotlib?
| Feature | Description |
|---|---|
| Visualizes Data | Converts raw data into easy-to-understand graphs |
| Customizable | You can change colors, styles, labels, and layouts |
| Works with NumPy & Pandas | Often used in data analysis |
| Multiple Plot Types | Line, bar, scatter, histogram, pie, etc. |
GUI Programming
A Graphical User Interface (GUI) is a visual way for users to interact with software using buttons, text boxes, labels, menus, etc. instead of typing commands in the console.
In Python, the
tkinter module is the standard GUI toolkit. It allows you to create windows, add widgets (like labels, buttons, text boxes), and handle user interactions.Working Flow of Tkinter:
| Step | Description |
|---|---|
| 1. Import Module | Import everything from tkinter (or use import tkinter as tk). |
| 2. Create Main Window | Create a main GUI window using Tk(). |
| 3. Add Widgets | Add GUI components like Labels, Buttons, Entries, etc. |
| 4. Place Widgets | Use geometry managers (pack(), grid(), place()) to position them. |
| 5. Define Events/Functions | Define functions for user actions (like button clicks). |
| 6. Run Main Loop | Run the mainloop() — keeps the window open and listens for user events. |
Tkinter Widgets:
| Widget | Purpose |
|---|---|
| Label | Display text or images. |
| Entry | Accept single-line text input. |
| Button | Perform an action when clicked. |
| Text | Accept multi-line text input. |
| Checkbutton / Radiobutton | Choose options. |
| Frame | Container for grouping widgets. |
Example:
from tkinter import *
from tkinter import messagebox
# Create main window
root = Tk()
root.title("Simple Widgets Example")
root.geometry("300x300")
# Label
label1 = Label(root, text="Enter your name:", font =("Times New Roman", 20))
label1.pack()
# Entry (for user input)
entry1 = Entry(root) # define Entry properly here
entry1.pack()
# Checkbutton
check_var = IntVar()
check1 = Checkbutton(root, text="I like Python", variable=check_var)
check1.pack()
# Radiobuttons
radio_var = StringVar(value="None")
radio1 = Radiobutton(root, text="Male", variable=radio_var, value="Male")
radio2 = Radiobutton(root, text="Female", variable=radio_var, value="Female")
radio1.pack()
radio2.pack()
# Function for button click
def show_data():
name = entry1.get() # gets text from Entry
gender = radio_var.get()
likes = "Yes" if check_var.get() == 1 else "No"
messagebox.showinfo("Details", f"Name: {name}\nGender: {gender}\nLike Python: {likes}")
# Button
button1 = Button(root, text="Show Details", command=show_data)
button1.pack(pady=10)
root.mainloop()
from tkinter import messagebox
# Create main window
root = Tk()
root.title("Simple Widgets Example")
root.geometry("300x300")
# Label
label1 = Label(root, text="Enter your name:", font =("Times New Roman", 20))
label1.pack()
# Entry (for user input)
entry1 = Entry(root) # define Entry properly here
entry1.pack()
# Checkbutton
check_var = IntVar()
check1 = Checkbutton(root, text="I like Python", variable=check_var)
check1.pack()
# Radiobuttons
radio_var = StringVar(value="None")
radio1 = Radiobutton(root, text="Male", variable=radio_var, value="Male")
radio2 = Radiobutton(root, text="Female", variable=radio_var, value="Female")
radio1.pack()
radio2.pack()
# Function for button click
def show_data():
name = entry1.get() # gets text from Entry
gender = radio_var.get()
likes = "Yes" if check_var.get() == 1 else "No"
messagebox.showinfo("Details", f"Name: {name}\nGender: {gender}\nLike Python: {likes}")
# Button
button1 = Button(root, text="Show Details", command=show_data)
button1.pack(pady=10)
root.mainloop()
Code after adding dialog box:
from tkinter import *
from tkinter import messagebox
# Create main window
root = Tk()
root.title("Simple Widgets Example")
root.geometry("300x300")
# Label
label1 = Label(root, text="Enter your name:", font =("Times New Roman", 20))
label1.pack()
# Entry (for user input)
entry1 = Entry(root) # define Entry properly here
entry1.pack()
# Checkbutton
check_var = IntVar()
check1 = Checkbutton(root, text="I like Python", variable=check_var)
check1.pack()
# Radiobuttons
radio_var = StringVar(value="None")
radio1 = Radiobutton(root, text="Male", variable=radio_var, value="Male")
radio2 = Radiobutton(root, text="Female", variable=radio_var, value="Female")
radio1.pack()
radio2.pack()
# Function for button click
def show_data():
name = entry1.get() # gets text from Entry
gender = radio_var.get()
likes = "Yes" if check_var.get() == 1 else "No"
messagebox.showinfo("Details", f"Name: {name}\nGender: {gender}\nLike Python: {likes}")
# ---------- Added Dialog Box Section ----------
dialog = Toplevel(root)
dialog.title("User Details")
dialog.geometry("250x150")
Label(dialog, text="User Details", font=("Times New Roman", 16, "bold")).pack(pady=5)
Label(dialog, text=f"Name: {name}").pack(pady=2)
Label(dialog, text=f"Gender: {gender}").pack(pady=2)
Label(dialog, text=f"Likes Python: {likes}").pack(pady=2)
Button(dialog, text="Close", command=dialog.destroy).pack(pady=10)
# ----------------------------------------------
# Button
button1 = Button(root, text="Show Details", command=show_data)
button1.pack(pady=10)
root.mainloop()
Databases
1. Install the MySQL Connector
First, install MySQL on your device. After installation,You need to install a connector so that Python can talk to MySQL.
In your terminal or command prompt, type:
pip install mysql-connector-python
2. Import the Connector
In your Python file, import it:
import mysql.connector
3. Establish a Connection
Connect to your MySQL server using your database credentials:
mydb = mysql.connector.connect(
host="localhost", # Your host, usually localhost
user="root", # Your MySQL username
password="your_password",# Your MySQL password
database="testdb" # Your database name
)
4. Create a Cursor
A cursor helps you execute SQL queries:
mycursor = mydb.cursor()
5. Create a Table
mycursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")
6. Insert Data
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
val = ("Swati", 22)
mycursor.execute(sql, val)
mydb.commit() # Save the changes
print(mycursor.rowcount, "record inserted.")
7. Fetch Data
mycursor.execute("SELECT * FROM students")
result = mycursor.fetchall()
for row in result:
print(row)
8. Close the Connection
Always close the connection when done:
mydb.close()
Example
import mysql.connector
# Connect to database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="testdb"
)
# Create cursor
mycursor = mydb.cursor()
# Insert data
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
val = ("Swati", 22)
mycursor.execute(sql, val)
mydb.commit()
# Retrieve data
mycursor.execute("SELECT * FROM students")
for x in mycursor.fetchall():
print(x)
# Close
mydb.close()
Comments
Post a Comment