UNIT - V
Matplotlib is a powerful and widely-used Python library for creating static,
animated and interactive data visualizations.
Matplotlib offers a wide variety of plots such as line charts, bar charts,
scatter plot and histograms making it versatile for different data analysis tasks.
The library is built on top of NumPy making it efficient for handling large
datasets. It provides a lot of flexibility in code.
Data Visualization with Pyplot using Matplotlib
Matplotlib provides a module called pyplot which offers a MATLAB-like
interface for creating plots and charts.
It simplifies the process of generating various types of visualizations by
providing a collection of functions that handle common plotting tasks.
Matplotlib supports a variety of plots including line charts, bar charts,
histograms, scatter plots, etc. Let’s understand them with implementation using
pyplot.
1. Line Chart
Line chart is one of the basic plots and can be created using
the plot() function. It is used to represent a relationship between two data X and
Y on a different axis.
Example:
import [Link] as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
[Link](x, y)
[Link]("Line Chart")
[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()
Output:
2. Bar Chart
A bar chart is a graph that represents the category of data with
rectangular bars with lengths and heights that is proportional to the values
which they represent.
The bar plots can be plotted horizontally or vertically. A bar chart describes
the comparisons between the different categories. It can be created using the
bar() method.
Example:
import [Link] as plt
import pandas as pd
data = pd.read_csv('[Link]')
x = data['day']
y = data['total_bill']
[Link](x, y)
[Link]("Tips Dataset")
[Link]('Total Bill')
[Link]('Day')
[Link]()
Output:
3. Histogram
A histogram is basically used to represent data provided in a form of some
groups. It is a type of bar plot where the X-axis represents the bin ranges while
the Y-axis gives information about frequency. The hist() function is used to
compute and create histogram of x.
A histogram is used to represent the frequency distribution of a set of
continuous data. It divides the data into bins and counts how many values fall
into each bin.
Example:
import [Link] as plt
import pandas as pd
data = pd.read_csv('[Link]')
x = data['total_bill']
[Link](x)
[Link]("Tips Dataset")
[Link]('Frequency')
[Link]('Total Bill')
[Link]()
Output:
4. Scatter Plot
Scatter plots are used to observe relationships between variables.
The scatter() method in the matplotlib library is used to draw a scatter plot.
Example:
import [Link] as plt
import pandas as pd
data = pd.read_csv('[Link]')
x = data['day']
y = data['total_bill']
[Link](x, y)
[Link]("Tips Dataset")
[Link]('Total Bill')
[Link]('Day')
[Link]()
Output:
5. Pie Chart
Pie chart is a circular chart used to display only one series of data. The area of
slices of the pie represents the percentage of the parts of the data. The slices of
pie are called wedges. It can be created using the pie() method.
Example:
import [Link] as plt
import pandas as pd
data = pd.read_csv('[Link]')
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR',]
data = [23, 10, 35, 15, 12]
[Link](data, labels=cars)
[Link]("Car data")
[Link]()
Output:
Graphical User Interfaces (GUIs) Using Python
In Python, Tkinter is the standard library for creating Graphical User
Interfaces (GUIs). It allows you to build desktop applications with various widgets
like labels, buttons, text fields, dialog boxes, and more.
Tkinter is simple to use and is available with most Python installations,
making it a great choice for beginners.
Here’s a guide on creating a simple GUI with Tkinter and using widgets like
Label, Text, Button, Info Dialog Boxes, Radiobutton, and Checkbutton.
1. Creating a Basic Tkinter Window
You begin by creating a main window (Tk object) where you can add widgets.
Here's an example of setting up the main window:
# Create main window
root = [Link]()
# Set window title
[Link]("Tkinter GUI Example")
# Set window size
[Link]("400x300")
Now, let's look at how to add various widgets.
2. Label Widget
The Label widget is used to display text or images in a window. It is commonly
used to display static information.
# Create a label widget
label = [Link](root, text="Welcome to Tkinter!", font=("Arial", 14))
[Link]() # The pack method places the widget on the window
3. Text Widget
The Text widget allows you to create a multi-line text field where users can input
or view text.
# Create a text widget
text_field = [Link](root, height=5, width=40)
text_field.pack()
# Add default text to the Text widget
text_field.insert([Link], "Write something here...")
4. Creating Buttons
The Button widget is used to perform an action when clicked, like calling a function.
Example:
ex:
from tkinter import *
window=Tk()
[Link]("350x350")
def blue():
[Link](bg="blue");
def red():
[Link](bg="red");
def green():
[Link](bg="green");
def yellow():
[Link](bg="yellow");
bt1=Button(window,text="blue",command=blue)
[Link](column=0,row=5)
bt2=Button(window,text="red",command=red)
[Link](column=1,row=5)
bt3=Button(window,text="green",command=green)
[Link](column=2,row=5)
bt4=Button(window,text="yellow",command=yellow)
[Link](column=3,row=5)
[Link]()
In this example, when the user clicks the "Click Me" button, the message "Button clicked!" is
printed.
Change button foreground and background colors
You can change the foreground for a button or any other widget
using fg property.
Also, you can change the background color for any widget using bg property.
btn = Button(window, text="Click Me", bg="orange", fg="red")
5. Info Dialog Boxes
Tkinter provides the messagebox module to create various types of message
boxes like info, warning, or error dialogs.
# Create an info dialog box when a button is clicked
def show_info_dialog():
[Link]("Information", "This is an info dialog box!")
# Create a button to trigger the dialog
info_button = [Link](root, text="Show Info", command=show_info_dialog)
info_button.pack()
6. Radiobutton Widget
A Radiobutton is used when you need the user to select only one option from a set of predefined options.
7. Checkbutton Widget
A Checkbutton allows the user to choose one or more options from a set. Unlike
radiobuttons, checkbuttons can be selected or deselected independently.
sum of any two by using gui.
from tkinter import *
window=Tk()
[Link]("350x350")
lb1=Label(window,text="A Value : ")
[Link](column=0,row=0)
lb2=Label(window,text="B Value : ")
[Link](column=0,row=1)
lb3=Label(window,text="sum is :")
[Link](column=0,row=2)
txt1=Entry(window,width=10)
[Link](column=2,row=0)
txt2=Entry(window,width=10)
[Link](column=2,row=1)
txt3=Entry(window,width=10)
[Link](column=2,row=2)
def clicked():
[Link](0,END);
a=int([Link]())
b=int([Link]())
c=a+b
[Link](0,c);
bt=Button(window,text="OK",command=clicked)
[Link](column=2,row=3)
[Link]()
Getting Input in Python :
In Python, you can get user input using the input() function. This function
allows you to prompt the user to enter data, which is then returned as a string.
Here's an example of getting input from a user:
# Getting input from the user
name = input("Enter your name: ")
age = input("Enter your age: ")
# Display the input
print(name, “ you are “, age, “years old.")
Importing MySQL for Python
To interact with MySQL databases in Python, you need to install a library called
mysql-connector-python or PyMySQL. These libraries allow you to establish
connections with a MySQL database and execute SQL queries.
Installation:
You can install mysql-connector-python using pip:
pip install mysql-connector-python
Connecting with a MySQL Database
Once you have installed the mysql-connector-python library, you can establish
a connection to a MySQL database using the connect() method from the
[Link] module. To connect, you will need details such as the database
host, user, password, and the database name.
Example: Connecting to MySQL
import [Link]
# Establishing a connection to the MySQL server
connection = [Link](
host="localhost", # MySQL server address
user="root", # MySQL username
password="your_password",# MySQL password
database="your_database" # Name of the database
)
# Checking if the connection is successful
if connection.is_connected():
print("Connected to MySQL database")
# Closing the connection
[Link]()
Forming a Query in MySQL
MySQL queries are written using SQL (Structured Query Language). These
queries are used to interact with the database — to fetch, insert, update, or delete
data.
Basic SQL Query Examples:
1. SELECT Query: To fetch data from a table.
SELECT * FROM users;
This query fetches all rows and columns from the users table.
2. INSERT Query: To add a new record to a table.
INSERT INTO users (name, age) VALUES ('Alice', 25);
3. UPDATE Query: To modify existing data.
UPDATE users SET age = 26 WHERE name = 'Alice';
4. DELETE Query: To delete data from a table.
DELETE FROM users WHERE name = 'Alice';
Passing a Query to MySQL
Once you've connected to MySQL, you can pass SQL queries to the database
using a cursor. A cursor allows you to execute SQL queries and fetch results.
Example: Executing a SELECT Query
import [Link]
# Establishing the connection to the MySQL server
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="your_database"
)
# Create a cursor object to interact with the database
cursor = [Link]()
# Forming the query
query = "SELECT * FROM users"
# Executing the query
[Link](query)
# Fetching the results
result = [Link]()
# Displaying the result
for row in result:
print(row)
# Closing the cursor and connection
[Link]()
[Link]()
Example: Executing an INSERT Query
import [Link]
# Establishing the connection to the MySQL server
connection = [Link](
host="localhost",
user="root",
password="your_password",
database="your_database"
)
# Create a cursor object
cursor = [Link]()
# Forming the query
insert_query = "INSERT INTO users (name, age) VALUES (%s, %s)"
values = ("John", 30)
# Executing the insert query
[Link](insert_query, values)
# Committing the transaction (necessary for INSERT, UPDATE, DELETE queries)
[Link]()
print("Record inserted successfully")
# Closing the cursor and connection
[Link]()
[Link]()
IMP QUESTIONS FROM UNIT-5
ESSAY:
*1) Explain about plotting Data using Matplotlib?
*2) Explain GUI (Graphical User Interface) using the TKinter Module?
*3) Explain about connection with a database and forming a query in MYSQL
passing a query to MYSQL? (Data Base Connectivity in Python)
SHORT:
*1) Explain Importing MySQL for Python?
To interact with MySQL databases in Python, you need to install a library called
mysql-connector-python or PyMySQL. These libraries allow you to establish
connections with a MySQL database and execute SQL queries.
Installation:
You can install mysql-connector-python using pip:
pip install mysql-connector-python
python?
2)Explain about date and time functions?