Python Unit - 5
Python Unit - 5
GU Interface: The Tkinter Module; Window and Widgets; Layout Management- pack, grid and
place.
Python SQLite: The SQLite3 module; SQLite Methods- connect, cursor, execute, close; Connect
to Database; Create Table; Operations on Tables- Insert, Select, Update. Delete and Drop Records.
Data Analysis: NumPy- Introduction toNumPy, Array Creation using NumPy, Operations on
Arrays; Pandas- Introduction to Pandas, Series and DataFrames, Creating DataFrames from Excel
Sheet and .csv file, Dictionary and Tuples. Operations on DataFrames.
Data Visualisation: Introduction to Data Visualisation; Matplotlib Library; Different Types of
Charts using Pyplot- Line chart, Bar chart and Histogram and Pie chart.
Tkinter module
Tk was developed as a GUI extension for the Tcl(Transaction Control Language) scripting language by John
Ousterhout. The first release was in 1991. Tk proved as extremely successful in the 1990's, because it is easier
to learn and to use than other toolkits.
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast
and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk
GUI toolkit.
As Tk is very popular thus it has been ported to a variety of other scripting languages, including Perl (Perl/Tk),
Ruby (Ruby/Tk), and Python (Tkinter).
Page 1
GUI development
Python Programming 2022-23
portability and flexibility of Tk makes it the right tool which can be used to design and
implement a wide variety of commercial-quality GUI applications.
Python with Tkinter provides us a faster and efficient way in order to build useful applications that would have
taken much time if you had to program directly in C/C++ with the help of native OS system libraries.
Developing desktop based applications with tkinter is not a complex task.
Tkinter is that it is cross-platform, so the same code can easily work on Windows, macOS, and Linux.
Tkinter is a lightweight module.
It is simple to use.
Importing tkinter
from tkinter import * or import tkinter as t
Create a GUI window
import tinker or import tkinter as t
mw = Tk() mw = t.Tk()
mw.mainloop() mw.mainloop()
The mainloop() method is an infinite loop that is used to run the application. It waits for an event to occur and
processes the event till the window is closed.
Page 2
Output Python Programming 2022-23
title(): this method is used to give title for GUI window.
geometry(): this method is used to specify the width and height of window.
Introduction to Widgets
Widgets is a GUI component that is displayed on the screen and can perform a task as designed by the user.
Widgets are standard GUI elements such as buttons, labels, entry, menus etc.
The following tasks to perform to create a widgets on GUI.
1. Import the tkinter module.
2. Create main window for GUI
3. Set the title for root window.
4. Write the code for working with widgets.
5. Call mainloop() in order to take action on each event triggered by the user.
Page 3
Python Programming 2022-23
Page 4
2. Python
grid Programming 2022-23
3. place
These layout managers are used to place widgets on to the parent window. Their task is to arrangethe
position of the widget on the window.
1. pack: The position is defined with respect to the other widgets.
Syntax: widget_name.pack(options)
Ex: button.pack() Options are as follows
expand : It can have boolean values , True and False. If value is set to True then widget expands to fill any
space.If value is set to False then it is used in widget’s parent
Ex: button.pack(expand = True)
Program to create GUI with expand method.
import tkinter as tk
mw= tk.Tk()
mw.geometry("200x200")
button1=tk.Button(text="B1")
button2=tk.Button(text="B2")
button3=tk.Button(text="B3")
button1.pack(expand = True)
button2.pack(expand = True)
button3.pack(expand = True)
mw.mainloop()
fill : It is used to fill extra spaces allocated to it by pack(). This fill option has dimensions like – NONE
(default), X(fill horizontally), Y(fill vertically) or BOTH(fill horizontally and vertically)
Ex: button.pack(fill = ‘both’)
button.pack(fill = ‘x’)
Page 5
Programming = ‘none’)
Pythonbutton.pack(fill 2022-23
button.pack(fill = ‘y’)
Program to create GUI with fill method.
import tkinter as tkmw= tk.Tk()
mw.geometry("200x200")
button1=tk.Button(text="B1")
button2=tk.Button(text="B2")
button3=tk.Button(text="B3")
button4=tk.Button(text="B4")
button1.pack(fill = 'both')
button2.pack(fill = 'x')
button3.pack(fill = 'none')
button4.pack(fill = 'y')
mw.mainloop()
side: This option specifies which side to pack the widget against. If you want to pack widgets
vertically, use TOP which is the default value. If you want to pack widgets horizontally, use LEFT
Ex: button.pack(side = ‘top’)
button.pack(side = ‘bottom’)
button.pack(side=’left’)
button.pack(side=’right’)
Program to create GUI with button
import tkinter as tk
mw= tk.Tk()
mw.geometry("200x200")
button1=tk.Button(text="B1")
button2=tk.Button(text="B2")
Page 6
Python Programming
button3=tk.Button(text="B3") 2022-23
button4=tk.Button(text="B4")
button1.pack(side = 'top')
button2.pack(side = 'bottom')
button3.pack(side='left')
button4.pack(side='right')
mw.mainloop()
2. Grid: This allows to organize the widgets in a table like structure. It allows to position thewidgets
based on the position coordinates of the grid.
The methods used in grid layout are as follows.
Column and row: The coordinates that determine the position of the widget.
ipadx, ipady : tells how much horizontal and vertical padding must be provided outsidethe
widgets border.
padx, pady: tells how much horizontal and vertical padding must be provided outside thewidgets
border.
Columnspan: Tells how many rows are oocupied by the widget. The default value is 1.
Rowspan: Tells how many rows are occupied by the widget. The default value is 1.
sticky: It defines how a widget must stick to the cell when it is smaller than the cell.
W – stick to left E – stick to right
N – stick to top S – stick to bottom
Ex: Program to create a GUI using grid methods
import tkinter as tk
mw=0 tk.Tk()
labeluser=tk.Label(mw, text="user name")
labeluser.grid(column=0,row=0,ipadx=5, pady=5,sticky=tk.W+tk.N)
labelpwd=tk.Label(mw, text="password")
Page 7
Python Programming
labelpwd.grid(column=0,row=1,ipadx=5, pady=5,sticky=tk.W+tk.S) 2022-23
entryuser=tk.Entry(mw,width=20)
entryuser.grid(column=1,row=0,ipadx=5, pady=10,sticky=tk.N)
entrypwd=tk.Entry(mw,width=20)
entrypwd.grid(column=1,row=1,ipadx=10, pady=10,sticky=tk.S)
login=tk.Button(mw, text="Login")
login.grid(column=0,row=2,ipadx=10, sticky=tk.W)
mw.mainloop()
3. place(): It allows to place widgets in a window in an absolute or relative position.The place geometry
manager provides you with both absolute and relative positioning options.
Absolute positioning is specified by the x and y options.
Relative positions is specified by the relx and rely options.
To set the absolute width and height of the widget in pixels, you use the width and height options.
The place geometry manager also provides you with relative width and height using
the relwidth and relheight options.
The relwidth and relheight has a value of a floating-point number between 0.0 and 1.0. This value
represents a fraction of the width and height of the container.
Absolute Positon
Example : import tkinter as
tkmw= tk.Tk()
labeluser=tk.Label(mw, text="user name")
labelpwd=tk.Label(mw, text="password")
entryuser=tk.Entry(mw,width=20)
entrypwd=tk.Entry(mw,width=20)
login=tk.Button(mw, text="Login")
labeluser.place(x=10, y=5)
Page 8
Python Programming 2022-23
labelpwd.place(x=10, y=40)
entryuser.place(x=75, y=5)
entrypwd.place(x=75, y=40)
login.place(x=10, y=80)
mw.mainloop()
Relative positon
Ex: import tkinter as tkmw= tk.Tk()
labeluser=tk.Label(mw, text="user name")
labelpwd=tk.Label(mw, text="password")
entryuser=tk.Entry(mw,width=20)
entrypwd=tk.Entry(mw,width=20)
login=tk.Button(mw, text="Login")
labeluser.place(relx = 0.01, rely = 0.15)
labelpwd.place(relx = 0.01, rely = 0.35)
entryuser.place(relx = 0.35, rely = 0.15)
entrypwd.place(relx = 0.35, rely = 0.35)
login.place(relx=0.01, rely=0.55)
mw.mainloop()
Page 9
Python Programming 2022-23
Python SQLite
SQLite is embedded relational database management system. It is self-contained, server less, zero
configuration and transactional SQL database engine.
SQLite is free to use for any purpose commercial or private. In other words, "SQLite is an open
source, zero-configuration, self-contained, stand alone, transaction relational database engine
designed to be embedded into an application".
SQLite is different from other SQL databases because unlike most other SQL databases, SQLite does not
have a separate server process. It reads and writes directly to ordinary disk files. A complete SQL database
with multiple tables, indices, triggers, and views, is contained in a single disk file.
SQLite Features
Following is the features makes SQLite popular among other lightweight databases
SQLite is totally free: SQLite is open-source. So, no license is required to work with it.
SQLite is server less: SQLite doesn't require a different server process or system to operate.
SQLite is very flexible: It facilitates to work on multiple databases on the same session at the same
time.
Configuration Not Required: SQLite doesn't require configuration. No setup or administration
required.
SQLite is a cross-platform DBMS: Don't need a large range of different platforms like Windows,
Mac OS, Linux, and Unix. It can also be used on a lot of embedded operating systems like Symbian,
and Windows CE.
Storing data is easy: SQLite provides an efficient way to store data.
Provide large number of API's: SQLite provides API for a large range of programming languages.
Ex: .Net languages (Visual Basic, C#), PHP, Java, Objective C, Python and a lot of other programming
language.
SQLite 3 module
The SQLite3 module in Python provides a simple and convenient way to interact with SQLite
databases.
It allows to perform various database operations, such as creating tables, inserting data, querying data,
updating data, and deleting data.
Page 10
Python Programming 2022-23
An overview of the SQLite3 module and its functionality:
1. Importing the module
To use the SQLite3 module, need to import it in Python script:
Ex: import sqlite3
2. Connecting to a database
To establish a connection to a SQLite database, the connect () function is provided by the SQLite3
module. It takes the database file path as a parameter and returns a Connection object that represents the
connection to the database.
Ex: connection = sqlite3.connect ('database.db')
3. Creating a cursor:
After establishing a connection, need to create a Cursor object to execute SQL statements and interact
with the database. The Cursor object allows to execute queries, fetch results, and perform database
operations.
Ex: cursor = connection.cursor()
5. Committing changes
After executing SQL statements that modify the database, such as inserting, updating, or deleting data,
need to commit the changes to make them permanent using the commit() method of the Connection
object.
Ex: connection.commit()
6. Querying data
To retrieve data from the database, execute a SELECT query using the execute() method and then fetch
the results using methods like fetchone() (to fetch a single row) or fetchall() (to fetch all rows).
EX: cursor.execute("SELECT * FROM employees") rows =
cursor.fetchall()
for row in rows:print(row)
Page 11
Python Programming 2022-23
7. Closing the connection
It's important to close the connection after all the operations are performed.Connection is closed by
using the close () method of the Connection object.
Ex: connection. close ()
These are the basic steps involved in using the SQLite3 module to interact with an SQLitedatabase in
Python.
SQLite Methods
Import sqlite3 module
o import sqlite3 statement in the program.
o Using the classes and methods defined in the sqlite3module we can communicate with the SQLite
database.
cursor(): cursor() method of a connection class is to create a cursor object to execute SQLite
command/queries from Python.
Ex: cursor = connection.cursor()
execute () :The execute() methods execute the SQL query and return the result.
Ex: cursor.execute("SELECT * FROM employees")
fetchall() : fetches all the rows of a query result. It returns all the rows as a list of tuples. Anempty list
is returned if there is no record to fetch.
Ex: cursor.fetchall()
Page 12
Python Programming 2022-23
Ex: cursor.fetchone()
fetchmany():It returns the number of rows specified by size argument. When called repeatedly, this
method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are
available, it returns an empty list
Syntax: cursor.fetchmany(size)
Ex: cursor.fetchmany(3)
Page 13
Python Programming 2022-23
created automatically by sqlite3
If we look at the folder where our Python script is, we should see a new file called database.db. This file has been
created automatically by sqlite3
Operations on Table
Create
To create a table in SQLITE, use the CREATE TABLE statement.
Syntax: CREATE TABLE table_name (column1 datatype,column2 datatype, ...);
Ex: CREATE TABLE employees (id INTEGER PRIMARY KEY,name TEXT, age
INTEGER, city TEXT);
Insert
To insert data into a table, use the INSERT INTO statement.
Syntax: INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Page 14
Python Programming 2022-23
Ex: INSERT INTO employees (name, age, city) VALUES ('John', 25, 'New York');
Update:
To update existing data in a table, use the UPDATE statement.
Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...
WHEREcondition;
Here's an example that updates the age of an employee with a specific ID
Ex: UPDATE employees SET age = 30 WHERE id = 1;
Delete
To delete data from a table, use the DELETE FROM statement.
Syntax: DELETE FROM table_name
WHERE condition;
Here's an example that deletes an employee with a specific ID
Ex: DELETE FROM employees WHERE id = 1;
Select(Querying data)
To retrieve data from a table, use the SELECT statement.
Syntax: SELECT column1, column2, ...FROM table_name
WHERE condition;
Here's an example that selects all employees
Ex: SELECT * FROM employees;
Filtering data
You can use the WHERE clause to filter data based on specific conditions.
Syntax: SELECT column1, column2, ... FROM table_name
WHERE condition;
Here's an example that selects employees from a specific city
Ex: SELECT * FROM employees
WHERE city = 'New York';
Sorting data
You can use the ORDER BY clause to sort the data in a specific order.
Syntax: SELECT column1, column2, ... FROM table_name ORDER BY column_name[ASC|DESC];
Page 15
Python Programming 2022-23
Here's an example that selects employees sorted by age in ascending order
Ex: SELECT * FROM employees ORDER BY age ASC;
Data Analysis
Data Analysis is the technique of collecting, transforming, and organizing data to make future predictions
and informed data driven decisions.
NumPy
NumPy is the fundamental package for scientific computing with Python. It stands for “Numerical
Python.”
The name "NumPy" is short for "Numerical Python."
It is a homogeneous collection of elements with a fixed size in memory.
Arrays can have one or more dimensions and can store data of different types, such as integers, floating-point
numbers, or even complex numbers.
It supports:
N-dimensional array object
Broadcasting functions
Tools for integrating C/C++ and Fortran code
Useful linear algebra, Fourier transform, and random number capabilities
It is widely used in data analysis, and machine learning due to its performance, versatility, and extensive
set of mathematical functions.
Array creation:
NumPy provides various functions for creating arrays, such as numpy.array(), numpy.zeros(), numpy.ones(),
numpy.arange(), and numpy.random. These functions allow you to create arrays with specific shapes, initialize
them with specific values, or generate random numbers.
Page 16
Python Programming 2022-23
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2)
vnumpy.ones: Creates an array filled with ones. It will take parameter as shape that is numberof rows
and coloumns.
Ex: arr = np.ones((2, 3))# shape as argument
print(arr)
numpy.linspace: Creates an array with a specified number of evenly spaced values between a start and
end point.
arrayname = np.linspace(start, stop, step)
Ex: arr = np.linspace(0,1,5)
print(arr)
numpy.random: Generates arrays with random values. It takes shape as argument for randomvalues
between 0 and 1
Ex: arr = np.random.rand(3, 2)
print(arr7)
# low, high, shape as arguments for random integers between 1 and 10
Ex: arr = np.random.randint(1, 10, (2, 3))
print(arr8)
Page 17
Python Programming 2022-23
Arithmetic operations: Perform element-wise arithmetic operations such as addition,subtraction,
multiplication, division, and exponentiation on arrays.
add(): It is used to add two array elements.
Ex: arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])
arr_sum = add(arr1, arr2)
print(arr_sum)
Pow(): the pow() function returns the value of x to the value of y(xy)
arr_pow = arr1 ** 2
print(arr_pow)
Output: [ 1 4 9 16]
Page 18
Python Programming 2022-23
arr_sum = np.sum(arr)
print(arr_sum)
mean(): It is used to compute the mean. It takes parameter as array name.
Ex: arr = np.array([1, 2, 3, 4, 5])
arr_mean = np.mean(arr)
print(arr_mean)
median():It is used to compute the standard deviation. It takes parameter as array name.Ex: arr =
np.array([1, 2, 3, 4, 5])
arr_median = np.median(arr)
print(arr_median)
std(): It is used to compute the standard deviation. It takes parameter as array name.Ex: arr =
np.array([1, 2, 3, 4, 5])
arr_std = np.std(arr) print(arr_std)
min(): It takes parameter as array name and find the minimum number in array. Ex: arr =
np.array([1, 2, 3, 4, 5])
arr_min = np.min(arr) print(arr_min)
max (): It takes parameter as array name and returns the maximum number in array.
Ex: arr = np.array([1, 2, 3, 4, 5])
arr_max = np. max (arr)
print(arr_max)
minimum(): It takes parameter as two array name and returns the minimum number in twoarray.
Ex: arr = np.array([1, 2, 3, 4, 5])
arr1= np.array([3,7,1,6, 8]) arr_min =
np.minimum(arr,arr1) print(arr_min)
maximum(): It takes parameter as two array and returns the maximum number in two array.
Ex: arr = np.array([1, 2, 3, 4, 5])
arr1= np.array([3,7,1,6, 8])
arr_min = np. Maximum
(arr,arr1)
print(arr_min)
Page 19
Python Programming 2022-23
Array manipulation: NumPy provides various functions for reshaping, transposing,and concatenating
arrays.
reshape: Gives a new shape to an array without changing its data.
Ex: arr = np.array([[1, 2, 3], [4, 5, 6]])
arr_r = np.reshape(arr, (3, 2))
print(arr_r)
Mathematical functions: NumPy provides a wide range of mathematical functionsthat operate element-
wise on arrays.
exp(): It takes parameter as array and returns exponent of elements in array.Ex: arr =
np.array([1, 2, 3, 4])
arr_e = np.exp(arr)
print(arr_e)
sqrt(): It takes parameter as array and returns square root of elements in array.Ex: arr =
np.array([1, 2, 3, 4])
arr_s = np.sqrt(arr) print(arr_s)
sin():It takes parameter as array and returns sine value of elements in array.Ex: arr =
np.array([1, 2, 3, 4])
arr_sin = np.sin(arr) print(arr_sin)
Introduction to pandas
Pandas is a powerful and popular open-source Python library widely used for datamanipulation
and analysis.
Page 20
Python Programming 2022-23
It provides easy-to-use data structures and data analysis tools, making it a go-to library forworking
with structured and tabular data.
Pandas is built on top of NumPy, extending its capabilities with additional functionality
specifically designed for data manipulation tasks.
Features of pandas
Data structures: Pandas introduces two primary data structures, namely Series and DataFrame.
i. Series: A Series is a one-dimensional labelled array that can hold any data type. It is similar to a
column in a spread sheet or a single column of data in a NumPy array, with associated index
labels for each element.
ii. DataFrame: A DataFrame is a two-dimensional labelled data structure, resembling a table or a
spread sheet with rows and columns. DataFrames provide a convenient way to store, manipulate,
and analyze tabular data.
Data manipulation: Pandas provides a rich set of functions for data manipulation tasks, such as
filtering, sorting, merging, grouping, reshaping, and aggregating data.
Merging and joining: Pandas allows to merge or join multiple DataFrames based on common
columns or indices, enabling the combination of different datasets into a single dataset.
Grouping and aggregating: Pandas provides powerful tools for grouping data based on one or more
columns, and then performing aggregations or calculations on these groups.
Data input and output: Pandas supports reading and writing data in various file formats,including
CSV, Excel, SQL databases, and more.
Integration with other libraries: Pandas integrates well with other libraries in the Pythonsuch as
NumPy, Matplotlib, and scikit-learn.etc.
Series in Pandas
In Pandas, a Series is a one-dimensional labelled array-like data structure that can hold any data type.
It is similar to a column in a spread sheet.
Each element in a Series is associated with a unique label, called the index, which allows forefficient
data alignment and easy access to values.
The basic syntax to create a Series object in Pandas is as follows:
import pandas as pd
s = pd.Series(data, index)
Page 21
Python Programming 2022-23
Here, data can be a list, NumPy array, dictionary, or scalar value that represents the data you wantto store
in the Series.
index is an optional parameter that specifies the labels for each element in the Series. If not
provided, a default integer index starting from 0 is assigned.
Dataframe
In Pandas, a DataFrame is a two-dimensional labelled data structure that represents tabulardata, similar
to a table or a spreadsheet.
It consists of rows and columns, where each column can hold data of different types (e.g., integers,
floats, strings).
The DataFrame provides a flexible and efficient way to handle and manipulate structured data.
The DataFrame provides powerful indexing and alignment capabilities, making it easy toperform
data manipulations, analysis, and transformations.
To create a DataFrame in Pandas, you can use various methods. One common way is by passing a dictionary
of lists, arrays, or Series as input, where the keys of the dictionary represent column names, and the values
represent the data in each column.
Example: import pandas as pd
data = {
'Name': ['John', 'Jane', 'Mike', 'Lisa'], 'Age': [25, 30, 28, 35],
Page 22
Python Programming 2022-23
'City': ['New York', 'London', 'Paris', 'Tokyo']
}
df = pd.DataFrame(data) print(df)
Output:
Name Age City
0 John 25 New York
1 Jane 30 London
2 Mike 28 Paris
3 Lisa 35 Tokyo
In this example, a DataFrame is created from the dictionary data, where each key represents a column
name and the corresponding value represents the data in that column.
The resulting DataFrame is displayed, showing the columns and their respective data.
Page 23
Python Programming 2022-23
print(df_sheet1) # Display the DataFrames
print(df_sheet2)
Page 24
Python Programming 2022-23
The pd.DataFrame() function is called with the dictionary as the argument, and the resulting DataFrame
is stored in the variable df.
The DataFrame is created with three columns ('Name', 'Age', 'City'), and each column contains the data
provided in the dictionary. The DataFrame automatically assigns a numeric index to each row starting
from 0.
Operations on dataframes
Accessing and viewing data
df.head(n): Returns the first n rows of the DataFrame.
df.tail(n): Returns the last n rows of the DataFrame.
df[column_name] : Accesses a specific column by its name.
df.iloc[row_index] : Accesses data by its index position.
Filtering data
df.query('condition'): Filters the DataFrame using a query string.
df.loc[condition] : Filters the DataFrame using a Boolean condition.
Page 25
Python Programming 2022-23
Data visualization
Data visualization provides a good, organized pictorial representation of the data which makes it
easier to understand, observe, analyze.
Data visualization is an essential part of data analysis and exploration. It helps to understand patterns,
trends, and relationships within the data by representing it visually.
There are various libraries in Python that can be used for data visualization, such as Matplotlib, Seaborn,
and Plotly. Here's a brief overview of these libraries and how you can use them for data visualization:
Matplotlib
Matplotlib is a widely used plotting library in Python. Matplotlib is an easy-to-use, low-level data
visualization library. It provides a wide range of plots, including line plots, bar plots, scatter plots,
histograms, and more.
Example of creating a line plot using Matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5] # Sample data
y = [10, 20, 15, 25, 30]
plt.plot(x, y) # Creating a line plot
plt.xlabel('X-axis') plt.ylabel('Y-axis')plt.title('Line Plot') plt.show()
Pyplot: Pyplot is a sub-module of the Matplotlib library, which is a popular data visualization library in
Python. By importing the pyplot module from Matplotlib, can access to a wide range of functions and
Page 26
Python Programming 2022-23
methods that allow to create and manipulate figures, axes, and different types of charts.
2. Line Chart
A Line chart is a graph that represents information as a series of data points connected by a straight
line. In line charts, each data point or marker is plotted and connected with a line or curve.
Ex: import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 18, 20]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.show()
3. Bar Graphs
A bar graph plots data with the help of bars, which represent value on the y-axis and category on the x-
axis.
Ex: import matplotlib.pyplot as plt
x = ['A', 'B', 'C', 'D']
Page 27
Python Programming 2022-23
y = [15, 8, 12, 10]
plt.bar(x, y) plt.xlabel('Categories')
plt.ylabel('Values') plt.title('Bar Plot')
plt.show()
4. Pie Chart
A pie chart represents data as sectors of a circle, where the size of each sectorcorresponds to the
proportion or percentage it represents.
Pie charts are commonly used to show the composition or relative contribution ofdifferent
categories to a whole. T
They are effective in displaying categorical data and making comparisons betweendifferent
categories.
Page 28