PP_unit-5_notes
PP_unit-5_notes
5.2 Matplotlib
Matplotlib is a popular Python library used for creating static, animated, and interactive visualizations in Python. It
provides a wide range of plotting tools and features for creating high-quality graphs, charts, and plots.
Here are some of the key components and functions provided by Matplotlib:
Key Components:
Figure: The entire window or page where the plots and charts are drawn.
Axes: The area where data is plotted. It includes the X-axis, Y-axis, and the plot itself.
Axis: The X-axis and Y-axis, which define the scale and limits of the plot.
Artist: Everything that is drawn on the figure (such as lines, text, shapes) is an artist.
Installation:-
python -m pip install -U matplotlib
100
Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data
visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by
John Hunter in 2002.
Types of Matplotlib
Matplotlib comes with a wide variety of plots. Plots help to understand trends, and patterns, and to make correlations.
They’re typically instruments for reasoning about quantitative information.
Some of the sample plots are covered here.
Matplotlib Line Plot
Matplotlib Bar Plot
Matplotlib Histograms
Plot Matplotlib Scatter
Plot Matplotlib Pie Charts
Matplotlib Area Plot
By importing the matplotlib module, defines x and y values for a plotPython, plots the data using the plot() function and
it helps to display the plot by using the show() function . The plot() creates a line plot by connecting the points defined
by x and y values.
Eg:-
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x, y)
# function to show the plot
plt.show()
5.2.2 Matplotlib Bar Plot
101
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot the bar
plt.bar(x, y)
# function to show the plot
plt.show()
# Y-axis values
y = [10, 5, 8, 4, 2]
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Area Chart
plt.fill_between(x, y1, y2, color='skyblue', alpha=0.4, label='Area 1-2')
plt.plot(x, y1, label='Line 1', marker='o')
plt.plot(x, y2, label='Line 2', marker='o')
5.3 Numpy:-
Install Python
NumPypip install
numpy
Eg:-
import numpy as np
103
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted
into an ndarray:
Dimensions in Arrays
NumPy arrays can have multiple dimensions, allowing users to store data in multilayered structures.
Dimensionalities of array:
Name Example
Name Example
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
Example:-
import numpy as np
print(arr)
3-D arrays
Example:
import numpy as np
print(arr)
104
Lecture 28. Python Pandas
Install Pandas
To install pandas, you need Python and PIP installed in your system.
If you have Python and PIP installed already, you can install pandas by entering the following command in the
terminal:
pip install pandas
Import Pandas in Python We can import Pandas in Python using the import statement.
import pandas as pd
What can you do using Pandas?
Pandas are generally used for data science but have you wondered why? This is because pandas are used in conjunction
with other libraries that are used for data science. It is built on the top of the NumPy library which means that a lot of
structures of NumPy are used or replicated in Pandas. The data produced by Pandas are often used as input for plotting
functions of Matplotlib, statistical analysis in SciPy, and machine learning algorithms in Scikit-learn. Here is a list of
things that we can do using Pandas.
● Data set cleaning, merging, and joining.
● Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data.
● Columns can be inserted and deleted from DataFrame and higher dimensional objects.
● Powerful group by functionality for performing split-apply-combine operations on data sets.
● Data Visulaization
Pandas Series
A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python
objects, etc.). The axis labels are collectively called indexes.
Pandas Series is nothing but a column in an Excel sheet. Labels need not be unique but must be a hashable type. The
object supports both integer and label-based indexing and provides a host of methods for performing operations
involving the index.
105
Example 1:
# import pandas as pd
import pandas as pd
# simple array
data = [1, 2, 3, 4]
ser = pd.Series(data)
print(ser)
Example 2:-
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
data = np.array(['g','e','e','k','s'])
ser = pd.Series(data)
print(ser)
DataFrame
Pandas DataFrame is a two-dimensional data structure with labeled axes (rows and columns).
Creating Data Frame
In the real world, a Pandas DataFrame will be created by loading the datasets from existing storage, storage can be
SQL Database, CSV file, or an Excel file. Pandas DataFrame can be created from lists, dictionaries, and from a list
of dictionaries, etc.
Example:-
import pandas as pd
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks']
106
Lecture 29. GUI Programs
root.mainloop()
OUTPUT
107
Lecture 30. Tkinter and Python Programming
5.6 Tkinter
Python provides various options for developing graphical user interfaces (GUIs). Most important are listed below.
● Tkinter− Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this
option in this chapter.
● wxPython− This is an open-source Python interface for wxWindow shttp://wxpython.org.
● JPython− JPython is a Python port for Java which gives Python scripts seamless access to Java class
libraries on the local machine http://www.jython.org
Tkinter Programming
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.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps .
● Import the Tkinter module.
● Create the GUI application main window.
● Add one or more of the above-mentioned widgets to the GUI application.
● Enter the main event loop to take action against each event triggered by the user.
Geometry Management
108
Lecture 31. Tk Widgets
5.7 Tk Widget- All Tkinter widgets have access to specific geometry management methods, which have the purpose
of organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager classes:
pack, grid, and place.
● The pack() Method− This geometry manager organizes widgets in blocks before placing them in the parent
widget.
● The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
● The place() Method − This geometry manager organizes widgets by placing them in a specific position in the
parent widget (absolute positions).
WIDGETS
Label
ENTRY
● from tkinter import *
● top = Tk()
● L1 = Label(top, text = "User Name")
● L1.pack( side = LEFT)
● E1 = Entry(top, bd = 5)
● E1.pack(side = RIGHT)
● top.mainloop()
Output:
button
● # Code to demonstrate a button
● import Tkinter as tk
109
● root=tk.Tk()
● l=tk.Label(root,text="name",fg="red",bg="lightgreen")
● l.grid(row=0,column=0)
● e=tk.Entry(root)
● e.grid(row=0,column=1)
● b=tk.Button(root,text="click",fg="red",bg="blue")
● b.grid(row=1,column=1)
● root.mainloop()
OUTPUT
CheckButton
from tkinter import *
import tkinter
top = Tk()
CheckVar1 =
IntVar() CheckVar2
= IntVar() def
show():
print(CheckVar1.get()
)
print(CheckVar2.get()
)
C1.pack()
C2.pack()
B1.pack()
top.mainloop()
OUTPUT
110
Radiobutton (int as well as string)
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text = "Option 1", variable = var, value = 1,command =
sel)R1.pack( )
R2 = Radiobutton(root, text = "Option 2", variable = var, value = 2, command =
sel) R2.pack( )
R3 = Radiobutton(root, text = "Option 3", variable = var, value = 3, command =
sel) R3.pack( )
label =
Label(root)
label.pack()
root.mainloop()
OUTPUT
111
MessageBox (Showinfo)
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("300x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")
Frame
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = "Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text = "Blue", fg = "blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text = "Black", fg = "black")
blackbutton.pack( side = BOTTOM)
root.mainloop()
OUTPUT:-
112
Lecture 33. Python Programming with IDE
5.8 Python Programming with IDE- An integrated development environment (IDE) refers to a software
application that offers computer programmers with extensive software development abilities. IDEs most often
consist of a source code editor, build automation tools, and a debugger. Most modern IDEs have
intelligent code completion. In this article, you will discover the best Python IDEs currently available and present
in the market.
What Is an IDE?
An IDE enables programmers to combine the different aspects of writing a computer program.
IDEs increase programmer productivity by introducing features like editing source code, building executables,
and debugging.
An Integrated Development Environment (IDE) is a software application that provides tools and resources to
help developers write and debug code. An IDE typically includes
A compiler or interpreter
An integrated debugger
A code editor is a text editor program designed specifically for editing source code. It typically includes features
that help in code development, such as syntax highlighting, code completion, and debugging.
The main difference between an IDE and a code editor is that an IDE has a graphical user interface (GUI) while
a code editor does not. An IDE also has features such as code completion, syntax highlighting, and debugging,
which are not found in a code editor.
Code editors are generally simpler than IDEs, as they do not include many other IDE components. As such,
code editors are typically used by experienced developers who prefer to configure their development environment
manually.
i. IDLE
ii. PyCharm
iv. Jupyter
iii. Construct a program to read cities.csv dataset, remove last column and save it in an array. Save the last column
to another array. Plot the first two columns.(2023-24 odd sem)
iv. Construct a plot for following dataset using matplotlib : .(2023-24 odd sem)
v. Describe how to generate random numbers using NumPy. Write a python program to create an array of 5
random integers between 10 and 50. .(2023-24 even sem)
114