Python for Data Science: Laboratory Programs in Python

Seaborn plots, plot styling and customization

Laboratory Programs in Python

Python for Data Science: Laboratory Programs in Python : Data Visualization - Matplotlib and Seaborn: Seaborn plots, plot styling and customization


Ex 1. Bar plot - plotting techniques in seaborn

In [1]: import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

%matplotlib inline

health = pd.read_csv("d:/healthexp.csv")

res = sns.barplot(x='Country',y='Spending USD', data = health)

plt.show()

Output


Code explanation: In above code,

•  We have imported numpy, pandas, matplotlib and seaborn libraries.

•  Then we have loaded healthexp.csv file using read_csv function.

•  There are two columns in this file healthexp.csv Country and Spending_USD We will make use of them for displaying bar plot. On x‒axis the Country name will be displayed and on y‒axis the Spending_USD will be displayed.


Ex 2. Countplot - plotting techniques in seaborn

In [1]: import numpy as np

import pandas as pd

import matplotlib.pyplot as plt copalbrog?

import seaborn as sns

# read dataset

titanic = pd.read_csv("d:/titanic.csv")

print(titanic.head())

# create plot

sns.countplot(x = 'Pclass',hue='Sex', data = titanic)

plt.title('Survivors')

plt.show()

Output



Code explanation: In above code

•  Initially we have imported all the required libraries such as numpy, pandas, matplotlib and seaborn.

•  We have read the csv file named titanic.csv. This file is available on the internet, it can be downloaded for the purpose of learning data analysis. I have stored it at the D drive. Hence the command for reading this csv file is ‒

titanic = pd.read_csv("d:/titanic.csv")



Ex 3. Distribution plot - plotting techniques in seaborn

In [5]: import numpy as np

import pandas as pd

import matplotlib.pyplot as plt.

import seaborn as sns

#read dataset

health = pd.read_csv("d:/healthexp.csv")

#display sample

print(health.head())

#create plot

res =sns.displot(x='Spending USD', kde = True, bins = 20, data = health)

plt.show()

Output



Code explanation: In above code,

 • Initially we have imported all the required libraries such as numpy, pandas, matplotlib and seaborn.

•  We have read the csv file named healthexp.csv. This file is available on the internet, it can be downloaded for the purpose of learning data analysis. I have stored it at the D drive. Hence the command for reading this csv file is ‒

health = pd.read_csv("d:/healthexp.csv")



Ex 4. Heatmap - plotting techniques in seaborn

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

data1 = np.random.randint(low=1,high=100,size=(10,10))

#display sample

print(data1)

#create plot

res =sns.heatmap(data = data1)

plt.show()

Output


Code explanation:

•  At the beginning of the code, all the necessary Python library files are imported.

• Then using the random.randint function the data set is obtained. The random.randint( ) is a NumPy library function that returns an array of random integers that are discrete uniform distribution of the specified dtype in the half‒open interval [low, high).

•  The sample is then displayed using print method.

• Then using heatmap function and plt.show() function the map is displayed for this sample data set.


Ex 5. Scatterplot - plotting techniques in seaborn

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

health = pd.read_csv("d:/healthexp.csv")

# Display sample

print(health.head())

# Create plot

res=sns.scatterplot(x='Country',y='Spending_USD',hue='Life_Expectancy',data=health) plt.show()

Output


Code explanation: In above code,

•  We have imported required library files such as matplotlib, pandas, numpy and seaborn.

•  Then using read_csv function we have read the healthexp.csv file.

•  First five records are displayed on the console.

• Then using scatterplot function the graph is plotted.

  Finally using plt.show() function the graph is displayed as output.



Ex 6. Linear regression plot - plotting techniques in seaborn

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

health = pd.read_csv("d:/healthexp.csv")

#display sample

print(health.head())

#create plot

res =sns.lmplot(x='Year',y='Spending_USD',hue='Country', data=health)

plt.show()

Output


Code explanation: In above code,

•  We have imported required library files such as matplotlib, pandas, numpy and seaborn.

•  Then using read_csv function we have read the healthexp.csv file.

•  First five records are displayed on the console.

•  Then using implot function the graph is plotted.

•  Finally using plt.show() function the graph is displayed as output.



Ex 7. Boxplot - plotting techniques in seaborn

In [7]: import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

health = pd.read_csv("d:/healthexp.csv")

#display sample

print(health.head())

#create plot

res sns.boxplot (x='Country',y='Life Expectancy', data=health)

plt.show()

Output


Ex 8. Pairplot - plotting techniques in seaborn

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

%matplotlib inline

flights = pd.read_csv("d:/flights.csv")

print(flights.head())

res = sns.pairplot(flights)

plt.show()

Output


Ex 9. Built‒in themes - Styling Your Plot

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

# read dataset

titanic = pd.read_csv("d:/titanic.csv")

print(titanic.head())

# create plot

sns.set_style("whitegrid")

sns.countplot(x = 'Pclass',hue='Sex', data = titanic)

plt.title('Survivors')

plt.show()

Output

Survivors


Ex 10. Scaling plots - Styling Your Plot

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

# read dataset

titanic = pd.read_csv("d:/titanic.csv")

print(titanic.head())

# create plot

sns.set_style("whitegrid")

sns.set_context("poster")

sns.countplot(x = 'Pclass',hue='Sex', data = titanic)

plt.title('Survivors')

plt.show()

Output


Ex 11. Setting the color palette - Styling Your Plot

Syntax

set_palette(palette, n_colors=None, desat=None, color_codes=False)

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

#read dataset

titanic = pd.read_csv("d:/titanic.csv")

print(titanic.head())

# create plot

sns.set_context("paper")

sns.set_palette("flare")

sns.countplot(x = 'Pclass',hue='Sex', data = titanic)

plt.title('Survivors')

plt.show()

Output


Ex 12. Setting title, X‒axis label and Y‒axis label - Styling Your Plot

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

# read dataset

titanic = pd.read_csv("d:/titanic.csv")

print(titanic.head())

# create plot

res=sns.countplot(x = 'Pclass',hue='Sex',data= titanic)

res.set_title("Titanic Survivors', fontdict={'size': 20, 'weight': 'bold'})

res.set_xlabel('Class', fontdict={'size': 10})

res.set_ylabel('count of Persons', fontdict={'size': 10})

plt.show()

Output


Ex 13. The 3D scatter plot - 3D Plot of Surface

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()

# Add a 3D subplot

ax = fig.add_subplot(111, projection='3d')

# Generate sample data

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

y = np.array([5, 3, 8, 12, 7, 9, 4, 6, 10, 15])

z = np.array([10, 12, 14, 8, 6, 9, 11, 7, 5, 13])

# Create a 3D scatter plot

ax.scatter(x, y, z, color='brown', marker='0')

# Set custom tick marks

ax.set_xticks([1, 3, 5, 7, 9])

ax.set_yticks([3, 6, 9, 12, 15])

ax.set_zticks([5, 7, 9, 11, 13])

ax.set_xlabel("X‒axis")

ax.set_ylabel("Y‒axis")

ax.set_zlabel("Z‒axis")

ax.set_title("Simple 3D Scatter Plot Demo")

plt.show()

Output

Simple 3D Scatter Plot Demo


Code explanation: In above code,

1) We have imported three library files

•  numpy: Helps us create and manipulate arrays (for x, y, z data).

•  matplotlib.pyplot: Used for creating plots and visualizations.

•  mpl_toolkits.mplot3d: Allows us to create 3D plots in Matplotlib.

2) plt.figure() : Creates an empty figure (window) where we can add plots.

3) fig.add_subplot(111, projection='3d'): Adds a 3D subplot inside the figure. 111 means 1 row, 1 column, and 1st (only) subplot. projection='3d' tells Matplotlib to create a 3D plot instead of the default 2D.

4) We create three arrays (x, y, z), each containing 10 values. These values represent coordinates in a 3D space. Each (x, y, z) point is one dot in the 3D scatter plot.

5) ax.scatter(x, y, z, color='brown', marker='o') : Plots brown dots (o) at (x, y, z) positions.

6) Then we set Tick marks on x,y and z axis. Tick marks are the numbers shown on the axes.

7) Then the x, y and z axis labels and title to the plot is created.

8) plt.show(): Displays the figure with the 3D scatter plot. Until we call plt.show(), nothing appears on the screen.


Ex 14. The 3D line plot - 3D Plot of Surface

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

x = [1, 2, 3, 4, 5]

y = [2, 3, 5, 7, 11]

z = [1, 4, 6, 8, 10]

fig = plt.figure()

fig.add_subplot(111, projection='3d')

ax.plot(x, y, z, marker='0')

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

ax.set_title('Simple 3D Line Plot Demo')

plt.show()

Output

Simple 3D Line Plot Demo


Code explanation: In above code,

1) We have imported three library files

•  numpy: Helps us create and manipulate arrays (for x, y, z data).

•  matplotlib.pyplot : Used for creating plots and visualizations.

•  mpl_toolkits.mplot3d: Allows us to create 3D plots in Matplotlib.

2) plt.figure() : Creates an empty figure (window) where we can add plots.

3) fig.add_subplot(111, projection='3d'): Adds a 3D subplot inside the figure. 111 means 1 row, 1 column, and 1st (only) subplot. projection='3d' tells Matplotlib to create a 3D plot instead of the default 2D.

4) We create three arrays (x, y, z), then using ax.plot(x, y, z, marker='0') we draw a 3D line with marker for each point.

5) Then the x,y and z axis labels and title to the plot is created.

6) plt.show(): Displays the figure with the 3D line plot.



Ex 15. The 3D surface plot - 3D Plot of Surface

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

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

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

x, y = np.meshgrid(x, y)

z = x**3+ y**3 # Example surface

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

asurf = ax.plot_surface(x, y, z, cmap='plasma')

ax.set_xlabel('X axis')

ax.set_ylabel('Y axis')

ax.set_zlabel('Z axis')

ax.set_title('Simple 3D Surface Plot Demo')

plt.show()

Output

Simple 3D Surface Plot Demo



Ex 16.

Create an intriguing 3D plot where the x values stretch from 0 to 10.

Let y follow the parabolic path y = x^2.

Let z shoot up in a cubic trajectory z = x^3.

1) Draw a stunning blue line

2) Customize the tick marks on all axes to guide the path.

3) Add a stylish background color to your plot.

Solution :

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

# Data for plotting

x = np.linspace(0, 10, 100)

y = x**2

z = x**3

# Create a 3D plot

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D line

ax.plot(x, y, z, color='blue')

# Changing tick marks for all axes

ax.set_xticks([0, 2, 4, 6, 8, 10])

ax.set_yticks([0, 20, 40, 60, 80, 100])

ax.set_zticks([0, 200, 400, 600, 800, 1000])

# Changing the background color of the plot

ax.set_facecolor('lightgreen')

# Adding labels and title

ax.set_xlabel('X‒axis')

ax.set_ylabel('Y‒axis')

ax.set_zlabel('Z‒axis')

ax.set_title('3D Plotting Demo with Custom Ticks and Background Color')

plt.show()

Output

3D Plotting Demo with Custom Ticks and Background Color


 

Ex 17.

Create a 3D bar chart where:

x = [1, 2, 3, 4, 5]

y=[10, 20, 30, 40, 50]

z=0 (all bars start from height 0)

Heights of bars = [5, 10, 15, 20, 25]

Use ax.bar3d(x, y, z, dx, dy, dz) to create bars

Solution :

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

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

y = np.array([10, 20, 30, 40, 50])

z = np.zeros(5)  # All bars start from height 0

dx = np.ones(5)  # Width of bars

dy= np.ones(5)  # Depth of bars

dz = np.array([5, 10, 15, 20, 25])  # Heights of bars

# Create a 3D plot

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D bars

ax.bar3d(x, y, z, dx, dy, dz, color='red')

# Adding labels and title

ax.set_xlabel('X‒axis')

ax.set_ylabel('Y‒axis')

ax.set_zlabel('Z‒axis')

ax.set_title('*************     3D Bar Chart Demo     ************)

# Show plot

plt.show()

Output


Python for Data Science: Laboratory Programs in Python : Tag: Computer Programming, Python, Data Science : Laboratory Programs in Python - Seaborn plots, plot styling and customization


Python for Data Science: Laboratory Programs in Python



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation