Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

EXPERIMENT-2.

3
AIM- Study Different Basic Functions of Matplotlib and
Seaborn Libraries
1. Represent a bar graph of the categorical feature of the student_result.csv dataset

In [18]:
import pandas as pd
import matplotlib.pyplot as plt

# Load the dataset


df = pd.read_csv('C:/Users/kriti/Downloads/student_result.csv')

# Assuming the categorical feature column is named "result"


result_counts = df['result'].value_counts()

plt.bar(result_counts.index, result_counts.values)
plt.xlabel('Result')
plt.ylabel('Count')
plt.title('Distribution of Student Results')

plt.show()

2.Display the marks of the last 10 students of the subject- ‘Maths’ and depict them using a bar graph (The name
of those students are as mentioned- ‘Raj, Sanjay, Abhisekh, John, Saurav, Sikha, Gayatri, Nisha, Mahesh,
Parvati’

In [19]:
import pandas as pd
import matplotlib.pyplot as plt

# Load the dataset


df = pd.read_csv('C:/Users/kriti/Downloads/student_result.csv')

# Filter data for 'Maths' subject and the last 10 students


filtered_df = df.tail(10)

# Create a bar graph


Loading [MathJax]/extensions/Safe.js
plt.bar(range(len(filtered_df)), filtered_df['math'])
plt.xlabel('Student Index')
plt.ylabel('Math Marks')
plt.title('Marks of Last 10 Students in Maths')
plt.tight_layout()

plt.show()

3.Represent a subplot for the above students and the last 10 marks for three subjects- ‘English, Math, and
Bangla’. Use appropriate legend, Title, etc for each graph

In [20]:
import pandas as pd
import matplotlib.pyplot as plt

# Load the dataset


df = pd.read_csv('C:/Users/kriti/Downloads/student_result.csv')

# Filter data for the last 10 students


filtered_df = df.tail(10)

# Create subplots
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))

# Plot for English


axes[0].bar(range(len(filtered_df)), filtered_df['english'], color='b', label='English')
axes[0].set_title('English Marks')
axes[0].set_xlabel('Student Index')
axes[0].set_ylabel('Marks')
axes[0].legend()

# Plot for Math


axes[1].bar(range(len(filtered_df)), filtered_df['math'], color='g', label='Math')
axes[1].set_title('Math Marks')
axes[1].set_xlabel('Student Index')
axes[1].set_ylabel('Marks')
axes[1].legend()

# Plot for Bangla


axes[2].bar(range(len(filtered_df)), filtered_df['bangla'], color='r', label='Bangla')
axes[2].set_title('Bangla Marks')
axes[2].set_xlabel('Student Index')
axes[2].set_ylabel('Marks')
axes[2].legend()

plt.tight_layout()
plt.show()
Loading [MathJax]/extensions/Safe.js
1. Draw a Histogram as per the following detailsa. X-axis- 20 random values (between 10 and 100) b. Y axis-
bins should be – 5,10,15,20,25 c. Histtype=’stepfill’ d. Edge= Red

In [22]:
import numpy as np
import matplotlib.pyplot as plt

# Generate 20 random values between 10 and 100


random_values = np.random.randint(10, 101, 20)

# Define bin edges


bin_edges = [5, 10, 15, 20, 25]

# Create a histogram
plt.hist(random_values, bins=bin_edges, histtype='stepfilled', edgecolor='red', alpha=0.7)
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram of 20 Random Values')
plt.xticks(bin_edges)

plt.tight_layout()
plt.show()

1. Create two subplots of sepal width vs sepal length and petal length vs petal width. The subplots should be
in red and blue colors respectively

In [24]:
import seaborn as sns
Loading [MathJax]/extensions/Safe.js
import matplotlib.pyplot as plt
# Load the Iris dataset
iris = sns.load_dataset("iris")

# Set up the figure and subplots


plt.figure(figsize=(12, 6))

# Subplot 1: Sepal width vs Sepal length


plt.subplot(1, 2, 1)
sns.scatterplot(data=iris, x='sepal_length', y='sepal_width', color='red')
plt.title('Sepal Width vs Sepal Length')

# Subplot 2: Petal length vs Petal width


plt.subplot(1, 2, 2)
sns.scatterplot(data=iris, x='petal_length', y='petal_width', color='blue')
plt.title('Petal Length vs Petal Width')

plt.tight_layout()
plt.show()

1. Plot a pie chart using the following dataa. Subject Name= DAA, DBE, ML, DS, DL b. Subject_Mark=
90,70,78,45,68 NOTE- Use different colors for each slice

In [25]:
import matplotlib.pyplot as plt

# Subject names and marks


subject_names = ['DAA', 'DBE', 'ML', 'DS', 'DL']
subject_marks = [90, 70, 78, 45, 68]

# Different colors for each slice


colors = ['blue', 'green', 'orange', 'red', 'purple']

# Create a pie chart


plt.pie(subject_marks, labels=subject_names, colors=colors, autopct='%1.1f%%', startangle=
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title('Subject Marks Distribution')


plt.show()

Loading [MathJax]/extensions/Safe.js
1. Plot a pie chart using the following dataa. Subject= English, Odia, Hindi, Geography, Maths b. Study_hour=
4,8,6,2,4 NOTE- Use different colors for each slice

In [26]:
import matplotlib.pyplot as plt

# Subject names and study hours


subjects = ['English', 'Odia', 'Hindi', 'Geography', 'Maths']
study_hours = [4, 8, 6, 2, 4]

# Different colors for each slice


colors = ['blue', 'green', 'orange', 'red', 'purple']

# Create a pie chart


plt.pie(study_hours, labels=subjects, colors=colors, autopct='%1.1f%%', startangle=140)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

plt.title('Study Hours by Subject')


plt.show()

1. Plot a color map on the 3D surface using the following dataa. cmap= RdYlBl b. Values of the X and Y axis
should be between -1 to 1, stepping value should be 0.25

In [27]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Create a meshgrid for X and Y values


X = np.arange(-1, 1.25, 0.25)
Loading [MathJax]/extensions/Safe.js
Y = np.arange(-1, 1.25, 0.25)
X, Y = np.meshgrid(X, Y)

# Calculate Z values for the surface


Z = X**2 + Y**2

# Create a figure and 3D axes


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

# Create a colormap
cmap = plt.get_cmap('RdYlBu')

# Plot the 3D surface with the colormap


surf = ax.plot_surface(X, Y, Z, cmap=cmap)

# Add colorbar
cbar = fig.colorbar(surf, ax=ax, shrink=0.5, aspect=10)
cbar.set_label('Z values')

# Set labels for X, Y, and Z axes


ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# Set plot title


ax.set_title('3D Surface with Colormap')

plt.show()

1. Draw two different graphs using the species feature of the IRIS dataset using Matplotlib and Seaborn.
Mention key differences between them. (Represent both the graph within the same graph)

In [28]:
import seaborn as sns
import matplotlib.pyplot as plt

# Load the Iris dataset


iris = sns.load_dataset("iris")

# Set up the figure and subplots


plt.figure(figsize=(12, 6))

# Matplotlib Scatterplot
plt.subplot(1, 2, 1)
for species in iris['species'].unique():
subset = iris[iris['species'] == species]
Loading [MathJax]/extensions/Safe.js
plt.scatter(subset['sepal_length'], subset['sepal_width'], label=species)
plt.title('Matplotlib Scatterplot')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.legend()

# Seaborn Scatterplot
plt.subplot(1, 2, 2)
sns.scatterplot(data=iris, x='sepal_length', y='sepal_width', hue='species')
plt.title('Seaborn Scatterplot')
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')

plt.tight_layout()
plt.show()

1. Draw a correlation heatmap using all the numerical features (sepal length, sepal width, petal length, petal
width) of the IRIS dataset using Matplotlib and Seaborn. Mention key differences between them. (Represent
both the graph within the same graph)

In [29]:
import seaborn as sns
import matplotlib.pyplot as plt

# Load the Iris dataset


iris = sns.load_dataset("iris")

# Calculate the correlation matrix


correlation_matrix = iris.corr()

# Set up the figure and subplots


plt.figure(figsize=(12, 6))

# Matplotlib Correlation Heatmap


plt.subplot(1, 2, 1)
plt.imshow(correlation_matrix, cmap='coolwarm', interpolation='nearest')
plt.title('Matplotlib Correlation Heatmap')
plt.xticks(range(len(correlation_matrix)), correlation_matrix.columns, rotation=45)
plt.yticks(range(len(correlation_matrix)), correlation_matrix.columns)

# Seaborn Correlation Heatmap


Loading [MathJax]/extensions/Safe.js
plt.subplot(1, 2, 2)
sns.heatmap(correlation_matrix, cmap='coolwarm', annot=True)
plt.title('Seaborn Correlation Heatmap')

plt.tight_layout()
plt.show()

NAME-KRITIKA DAS

ROLLNO-CSE21068

REGD NO-2101020068

In [ ]:

Loading [MathJax]/extensions/Safe.js

You might also like