Python - Lab - Manual - B.Tech. - Sem-2 Aneek

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

Bachelor of Technology

LAB MANUAL
For

Department of Computer Science and Engineering


(CSE)
Bachelor of Technology (AIML)

Course Name: Data Analysis Using Python


Course Code: 130202120
Semester: 2nd

Submitted by:
Submitted to:
Manish Dahiya
Ms. Shabda
231302125
AIML Trainer

Faculty of Engineering and Technology


Contents of Course File

Sr. No. Content Page No.

1. Vision and Mission of the University 3

2. Vision and Mission of the Department 3

3. PEOs, POs, PSOs and SOs 4

4. Code of Ethics 7
5. Course Syllabus 8
6. Course Outcome and COs-POs, COs-SOs mapping of the course 9

7. List of Experiments 10

8. 1. Python Installation 11-

9. 2. Python Programming Basics

10. 3. Python Data Structures 24-26

11. 4. NumPy, Array & Vectorized Computation 27-34

12. 5. Data Manipulation with Pandas. 35-50

13. 6. Data Visualization in Python using Matplotlib and Seaborn 51-54


Vision of the University
To nurture individual’s excellence through value based, cross-cultural, integrated and holistic education adopting the
contemporary and advanced means blended with ethical values to contribute in building a peaceful and sustainable
global civilization.
Mission of the University

● To impart higher education at par with global standards that meets the changing needs of the society
● To provide access to quality education and to improve quality of life, both at individual and community
levels with advancing knowledge in all fields through innovations and ethical research.
● To actively engage with and promote growth and welfare of the surrounding community through suitable
extension and outreach activities
● To develop socially responsible citizens, fostering ethical values and compassion through participation in
community engagement, extension and promotion activities.
● To create competitive and coordinated environment wherein the individual develop skills and a lifelong
learning attitude to excel in their endeavours.
● To develop Centers of Excellence culminating in achieving the cutting-edge technology in all fields.

Vision of the Department


To be one of the top leaders who develops competitive and devoted professionals in the field of computer engineering
by providing cutting-edge knowledge in a variety of innovative technology areas, including artificial intelligence,
machine learning, data science, cybersecurity, Internet of Things (IoT), cloud computing, big data, software
development and more.
Mission of the Department
Our mission is to produce computer science experts who can address the challenges of the digital age. We achieve
this through high-quality education and practical training that prepares our students to contribute in an
impactful way to this field. Join us in cultivating the next generation of computer engineers and driving positive
change in the digital world.
Program Educational Objectives (PEOs)

PEO1: Graduates of the Computer Science and Engineering will contribute to the Nation’s growth through
their ability to solve diverse and complex computer science and engineering problems across a broad range
of application areas. (PEO1 is focused on Problem Solving)
PEO2: Graduates of the Computer Science and Engineering will be successful professionals, designing and
implementing Products & Services of global standards in the field of Computer Science & Engineering,
becoming entrepreneurs, Pursuing higher studies & research. (PEO 2 is focused on Professional Success)
PEO3: To install leadership qualities in graduates with a sense of confidence, professionalism and ethical
attitude to produce professional leaders for serving the society.
PEO3: Graduates of the Computer Science and Engineering Program will be able to adapt to changing
scenario of dynamic technology with an ability to solve larger societal problems using logical and flexible
approach in decision making. (PEO 3 is focused on Attaining Flexibility and Adaptability)
Program Outcomes (POs)

Engineering Graduates will be able to understand and apply the below mentioned PO’s.
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multi-disciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)

A Graduate of Computer Science and Engineering Program will be able to acquire the below mentioned
PSOs:
PSO1: Exhibit attitude for continuous learning and deliver efficient solutions for emerging challenges in the
computation domain.
PSO2: Apply standard software engineering principles to develop viable solutions for Information
Technology Enabled Services (ITES).

Student Outcomes (SOs)

CAC
Analyze a complex computing problem and to apply principles of computing and
SO1
other relevant disciplines to identify solutions.
Design, implement and evaluate a computing-based solution to meet a given set of
SO2
computing
requirements in the context of the program ‘s discipline.
SO3 Communicate effectively in a variety of professional contexts.
Recognize professional responsibilities and make informed judgments in
SO4
computing practice
based on legal and ethical principles.
Function effectively as a member or leader of a team engaged in activities
SO5
appropriate to the
program ‘s discipline.
Identify and analyse user needs and to take them into account in the selection,
SO6 creation, integration, evaluation, and administration of computing-based systems

EAC
An ability to identify, formulate, and solve complex engineering problems by
SO1
applying principles of engineering, science, and mathematics.
An ability to apply engineering design to produce solutions that meet specified needs
SO2 with consideration of public health, safety, and welfare, as well as global, cultural,
social, environmental, and economic factor.

SO3 An ability to communicate effectively with a range of audiences.


An ability to recognize ethical and professional responsibilities in engineering
SO4 situations and make informed judgments, which must consider the impact of
engineering solutions in global, economic, environmental, and societal contexts.

An ability to function effectively on a team whose members together provide


SO5
leadership, create a collaborative and inclusive environment, establish goals, plan
tasks, and meet objectives
An ability to develop and conduct appropriate experimentation, analyse and interpret
SO6
data, and use engineering judgment to draw conclusions.

SO7 An ability to acquire and apply new knowledge as needed, using appropriate learning
strategies.
Code of Ethics

I. To uphold the highest standards of integrity, responsible behaviour, and ethical conduct in
professional activities.
1. to hold paramount the safety, health, and welfare of the public, to strive to comply with
ethical design and sustainable development practices, to protect the privacy of others, and
to disclose promptly factors that might endanger the public or the environment;
2. to improve the understanding by individuals and society of the capabilities and societal
implications of conventional and emerging technologies, including intelligent systems.
3. to avoid real or perceived conflicts of interest whenever possible, and to disclose them
to affected parties when they do exist;
4. to avoid unlawful conduct in professional activities, and to reject bribery in all its forms;
5. to seek, accept, and offer honest criticism of technical work, to acknowledge and correct
errors, to be honest and realistic in stating claims or estimates based on available data, and
to credit properly the contributions of others;
6. to maintain and improve our technical competence and to undertake technological tasks
for others only if qualified by training or experience, or after full disclosure of pertinent
limitations;
II. To treat all persons fairly and with respect, to not engage in harassment or discrimination, and
to avoid injuring others.
7. to treat all persons fairly and with respect, and to not engage in discrimination based on
characteristics such as race, religion, gender, disability, age, national origin, sexual
orientation, gender identity, or gender expression;
8. to not engage in harassment of any kind, including sexual harassment or bullying
behaviour;
9. to avoid injuring others, their property, reputation, or employment by false or malicious
actions, rumours or any other verbal or physical abuses;
III. To strive to ensure this code is upheld by colleagues and co-workers.
10. to support colleagues and co-workers in following this code of ethics, to strive to
ensure the code is upheld, and to not retaliate against individuals reporting a violation.
1. Name of the Department- Computer Science Engineering

2. Data Analysis L T P
Course using Python -
Name Lab

3. 0 0 4
Course
Code

4. Type of Course (use tick Core() PE( ) OE ()


mark)

5. Pre- 6. Frequency Even Odd Either Every


requis (use tick ()
( ) Sem () Sem ()
ite (if marks)
any)

7. Total Number of Lectures, Tutorials, Practical (assuming 14 weeks of one semester)

Lectures = 0 Tutorials = 0 Practical = 28

8. Course Description

This course presents a gentle introduction into the concepts of data analysis, the role of a Data Analyst, and
the tools that are used to perform daily functions. You will gain an understanding of the data ecosystem and
the fundamentals of data analysis, such as data gathering or data mining. You will then learn the soft skills
that are required to effectively communicate your data to stakeholders, and how mastering these skills can
give you the option to become a data driven decision maker.
9. Learning objectives:
• Provide you with the knowledge and expertise to become a proficient data
scientist
• Demonstrate an understanding of statistics and machine learning concepts that are
vital for data science;
• Produce Python code to statistically analyse a dataset;
• Critically evaluate data visualisations based on their design and use for
Communicating stories from data.

10. Course Outcomes (COs):

1. Explain how data is collected, managed and stored for data science;
2. Understand the key concepts in data science, including their real-world applications and
the toolkit used by data scientists.
3. Implement data collection and management scripts using MongoDB.

11. List of Experiments

1. Python Installation
2. Python Programming Basics
3. Python Data Structures
4. NumPy, Array & Vectorized Computation
5. Data Manipulation with Pandas.
6. Data Visualization in Python using Matplotlib and Seaborn
COs-POs mapping of the course

P P PO P P PO P P P P P PO1 PS PS
O O 3 O O 6 O O O O1 O1 2 O1 O2
CO 1 2 4 5 7 8 9 0 1
CO-1 - - - 3 - 3 - - - - - - - 3

CO-2 - - 3 - - 3 - 3 - - - - -

CO-3 3 3 - 3 - 3 - - - - - - 3 -

a) Explicitly indicate which of the student outcomes listed in Criterion 3 or any other
outcomes are addressed by the course.
Python Installation
Installing Anaconda on Windows

Experiment No. 1
• Download the Anaconda installer from the following link
https://www.anaconda.com/products/individual#windows

Double click the installer to launch.


Note If you encounter issues during installation, temporarily disable your anti-
virus software during install, then re-enable it after the installation concludes. If
you installed for all users, uninstall Anaconda and re-install it for your user only
and try again.
Click Next.
Read the licensing terms and click “I Agree”.
Select an install for “Just Me” unless you’re installing for all users (which requires
Windows Administrator privileges) and click Next.
Select a destination folder to install Anaconda and click the Next button.
• Choose whether to add Anaconda to your PATH environment variable. We
recommend not adding Anaconda to the PATH environment variable, since
this can interfere with other software. Instead, use Anaconda software by
opening Anaconda Navigator or the Anaconda Prompt from the Start
Menu.
• Choose whether to register Anaconda as your default Python. Unless you
plan on installing and running multiple versions of Anaconda or multiple
versions of Python, accept the default and leave this box checked.
• Click the Install button. If you want to watch the packages Anaconda is
installing, click Show Details.
• Click the Next button.
• Optional: To install PyCharm for Anaconda, click on the link to
https://www.anaconda.com/pycharm.
• Or to install Anaconda without PyCharm, click the Next button.
• After a successful installation you will see the “Thanks for installing
Anaconda” dialog box:
• If you wish to read more about Anaconda.org and how to get started with
Anaconda, check the boxes “Anaconda Individual Edition Tutorial” and
“Learn more about Anaconda”.
• Click the Finish button.
Anaconda Navigator
Create New Notebook Document on Jupyter

Spyder
Python Programming Basics
Experiment No. 2
Q. Add Two Numbers with “+” Operator:
Here num1 and num2 are variables and we are going to add both variables with the +
operator in Python.

# Python3 program to add two numbers


num1 = 15
num2 = 12

# Adding two nos


sum = num1 + num2

# printing values
print("Sum of", num1, "and", num2 , "is", sum)

Output:
Sum of 15 and 12 is 27

Experiment No. 3
Q. Add Two Numbers with User Input:
In the below program to add two numbers in Python, the user is first asked to enter two
numbers, and the input is scanned using the Python input() function and stored in the
variables number1 and number2.
Then, the variable’s number1 and number2 are added using the arithmetic operator +,
and the result is stored in the variable sum.

# Python3 program to add two numbers

number1 = input("First number: ")


number2 = input("\n Second number: ")

# Adding two numbers


# User might also enter float numbers
sum = float(number1) + float(number2)
# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1,
number2, sum))

Output:
First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04

Experiment No. 4
Q. Add Two Numbers Using operator.add() Method:
Initialize two variables num1, and num2. Find sum using the operator.add() by passing
num1, and num2 as arguments and assign to sum. Display num1, num2 and sum.
# Python3 program to add two numbers

num1 = 15
num2 = 12

# Adding two nos


import operator
sum = operator.add(num1,num2)

# printing values
print("Sum of {0} and {1} is {2}" .format(num1,
num2, sum))

Output
Sum of 15 and 12 is 27

Python Data Structures

Experiment No. 5
Q. Add Two Numbers in Python Using Function
This program show adding two numbers in Python using function. We can define a
function that accepts two integers and returns their sum.
#To define a function that take two integers
# and return the sum of those two numbers
def add(a,b):
return a+b

#initializing the variables


num1 = 10
num2 = 5

#function calling and store the result into sum_of_twonumbers


sum_of_twonumbers = add(num1,num2)

#To print the result


print("Sum of {0} and {1} is {2};" .format(num1,
num2, sum_of_two numbers))

Output
Sum of 10 and 5 is 15;

Experiment No. 6
Q. Write a program in Python to make a simple calculator.

# Python program for simple calculator

# Function to add two numbers


def add(num1, num2):
return num1 + num2

# Function to subtract two numbers


def subtract(num1, num2):
return num1 - num2

# Function to multiply two numbers


def multiply(num1, num2):
return num1 * num2

# Function to divide two numbers


def divide(num1, num2):
return num1 / num2
print("Please select operation -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")

Experiment No. 7

Q. Create a Python program to find sum of elements in list (using for loop)

total = 0

# creating a list
list1 = [11, 5, 17, 18, 23]

# Iterate each element in list


# and add them in variable total
for ele in range(0, len(list1)):
total = total + list1[ele]

# printing total value


print("Sum of all elements in given list: ", total)

Output
Sum of all elements in given list: 74

Experiment No. 8

Q. Write a Python program to find sum of elements in list (using while loop)

total = 0
ele = 0

# creating a list
list1 = [11, 5, 17, 18, 23]

# Iterate each element in list


# and add them in variable total
while(ele < len(list1)):
total = total + list1[ele]
ele += 1

# printing total value


print("Sum of all elements in given list: ", total)

Output
Sum of all elements in given list: 74

Experiment No. 9
Q. Write a Python Program to count the number of vowels in a string.
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)

Output:
Case 1:
Enter string:Hello world
Number of vowels are:
3

Case 2:
Enter string:WELCOME
Number of vowels are:
3

Experiment No. 10
Q. Create a Python program and check how many dimensions the arrays
have
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Output:
0
1
2
3

Experiment No. 11
Q. Create an array with 5 dimensions using ndmin using a vector with values
1,2,3,4 and verify that last dimension has value 4
import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('shape of array :', arr.shape)
Output:
[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)

Experiment No. 12
Q. Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements


import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)

print(newarr)

Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Experiment No. 13
Q. Write Python code to demonstrate trigonometric function.

import numpy as np
# create an array of angles
angles = np.array([0, 30, 45, 60, 90, 180])

# conversion of degree into radians


# using deg2rad function
radians = np.deg2rad(angles)
# sine of angles
print('Sine of angles in the array:')
sine_value = np.sin(radians)
print(np.sin(radians))

# inverse sine of sine values


print('\n\n Inverse Sine of sine values:')
print(np.rad2deg(np.arcsin(sine_value)))

# hyperbolic sine of angles


print('\n\n Sine hyperbolic of angles in the array: ')
sineh_value = np.sinh(radians)
print(np.sinh(radians))

# inverse sine hyperbolic


print('\n\n Inverse Sine hyperbolic:')
print(np.sin(sineh_value))

# hypot function demonstration


base = 4
height = 3
print('\n\n hypotenuse of right triangle is:')
print(np.hypot(base, height))

Output:
Sine of angles in the array:
[0.00000000e+00 5.00000000e-01 7.07106781e-01 8.66025404e-01
1.00000000e+00 1.22464680e-16]

Inverse Sine of sine values:


[0.0000000e+00 3.0000000e+01 4.5000000e+01 6.0000000e+01
9.0000000e+01
7.0167093e-15]

Sine hyperbolic of angles in the array:


[ 0. 0.54785347 0.86867096 1.24936705 2.3012989
11.54873936]

Inverse Sine hyperbolic:


[ 0. 0.52085606 0.76347126 0.94878485 0.74483916 -
0.85086591]

hypotenuse of right triangle is:


5.0

Experiment No. 14
Q. Python code demonstrate statistical function.

import numpy as np
# construct a weight array
weight = np.array([50.7, 52.5, 50, 58, 55.63, 73.25, 49.5, 45])

# minimum and maximum


print('Minimum and maximum weight of the students: ')
print(np.amin(weight), np.amax(weight))
# range of weight i.e. max weight-min weight
print('\n Range of the weight of the students: ')
print(np.ptp(weight))

# percentile
print('\n Weight below which 70 % student fall: ')
print(np.percentile(weight, 70))

# mean
print('\n Mean weight of the students: ')
print(np.mean(weight))

# median
print('\n Median weight of the students: ')
print(np.median(weight))

# standard deviation
print('\n Standard deviation of weight of the students: ')
print(np.std(weight))

# variance
print('\n Variance of weight of the students: ')
print(np.var(weight))

# average
print('\n Average weight of the students: ')
print(np.average(weight))
Output:
Minimum and maximum weight of the students:
45.0 73.25

Range of the weight of the students:


28.25

Weight below which 70 % student fall:


55.317

Mean weight of the students:


54.3225

Median weight of the students:


51.6

Standard deviation of weight of the students:


8.052773978574091

Variance of weight of the students:


64.84716875

Average weight of the students:


54.3225

Experiment No. 15
Q. (a) creating series from ndarray
data = np.array(['a','b','c','d'])
print(data)
s_arr = pd.Series(data)
print(s_arr)

Output:
['a' 'b' 'c' 'd']
0 a
1 b
2 c
3 d
dtype: object

(b) creating series from dict


data = {'a' : 0., 'bat' : 1., 10: 2.3}
s_dict = pd.Series(data)
print(s_dict)

Output:
a 0.0
bat 1.0
10 2.3
dtype: float64

(c) changing the index


s_change = pd.Series(data,['bat',2,10])
print(s_change)

Output:
bat 1.0
2 NaN
10 2.3
dtype: float64

Experiment No. 16
Q. Create a DataFrame in Python using Pandas:
import pandas as pd
data = {'state':['Ohio', 'Delhi', 'Ohio', 'Nevada','Nevada','Nevada'],
'year':[2000,2003 ,2001 ,2000, 2001, 2002],
'pop':[1.5, 1.6, 5,3.9, 4, 6.7]}

#data
frame = pd.DataFrame(data)
print(frame)
frame = pd.DataFrame(data,[10,11,12,13,14,15],['year','state','pop'])
frame

Output:
state year pop
0 Ohio 2000 1.5
1 Delhi 2003 1.6
2 Ohio 2001 5.0
3 Nevada 2000 3.9
4 Nevada 2001 4.0
5 Nevada 2002 6.7

year state pop

1
2000 Ohio 1.5
0

1
2003 Delhi 1.6
1

1
2001 Ohio 5.0
2

1
2000 Nevada 3.9
3

1
2001 Nevada 4.0
4
year state pop

1
2002 Nevada 6.7
5

Experiment No. 17

Q. (a) Reorder the existing data to match a new set of labels.


(b) Insert missing value (NA) markers in label locations where no
data for the label existed.

import pandas as pd
# Create dataframe
info = pd.DataFrame({"P":[4, 7, 1, 8, 9],
"Q":[6, 8, 10, 15, 11],
"R":[17, 13, 12, 16, 14],
"S":[15, 19, 7, 21, 9]},
index =["Parker", "William", "Smith", "Terry", "Phill"])
# Print dataframe
info
Output:

# reindexing with new index values


info1=info.reindex(["P", "B", "R", "D", "E"],axis=1)
info1
Output:

# filling the missing values by 100


info1.reindex(["A", "B", "C", "D", "E",'F'], fill_value =100)
Output:

Experiment No. 18

import pandas as pd
import numpy as np

N=5

df = pd.DataFrame({
'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),
'x': np.linspace(0,stop=N-1,num=N),
'y': np.random.rand(N),
'C': np.random.choice(['Low','Medium','High'],N).tolist(),
'D': np.random.normal(100, 10, size=(N)).tolist()
})
Df

Output:

Experiment No. 19

Matplotlib Inline
The output of plotting commands is displayed inline within frontends
like the Jupyter notebook, directly below the code cell that produced
it. The resulting plots will then also be stored in the notebook
document. %matplotlib inline should be the first command before
import command

#%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
data = np.arange(10)
print(data)
plt.plot(data)
plt.show()
[0 1 2 3 4 5 6 7 8 9]
x = np.arange(0.0, 6.0, 0.01)
plt.plot(x, [x**2 for x in x]);
#plt.show()

Multiline Plot

plots are reset after each cell is evaluated, so for more complex plots
you must put all of the plotting commands in a single notebook cell
x = np.arange(0.0, 6.0, 0.01)
plt.plot(x, [x**2 for x in x])
plt.plot(x, [x**2.25 for x in x])
plt.plot(x, [x**2.5 for x in x]);

Experiment No. 20
Seaborn Session

import numpy as np
from matplotlib import pyplot as plt

def sinplot(flip=0.5):
x = np.linspace(0, 14, 100)
for i in range(1, 5):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)

sinplot()
plt.show()
import seaborn as sns
sns.set_style("dark")
sinplot()
plt.show()
sns.set_style("white")
sinplot()
sns.despine()
plt.show()
Qualitative or categorical palettes are best suitable to plot the
categorical data.

current_palette = sns.color_palette()
sns.palplot(current_palette)
plt.show()

Appending an additional character ‘s’ to the color passed to the color


parameter will plot the Sequential plot.

current_palette = sns.color_palette()
sns.palplot(sns.color_palette("Reds"))
plt.show()

Diverging palettes use two different colors. Each color represents


variation in the value ranging from a common point in either direction.

Assume plotting the data ranging from -1 to 1. The values from -1 to 0


takes one color and 0 to +1 takes another color.

By default, the values are centered from zero. You can control it with
parameter center by passing a value.

current_palette = sns.color_palette()
sns.palplot(sns.color_palette("BrBG", 7))
plt.show()

You might also like