0% found this document useful (0 votes)
9 views18 pages

Exp 2 SDK Ok

The document provides a comprehensive guide on data visualization techniques in Python using Matplotlib and Seaborn. It includes various examples such as line charts, bar charts, scatter plots, histograms, box plots, facet grids, heat maps, and pair plots, demonstrating how to create each type of visualization with code snippets. Each example is accompanied by a brief description and expected output.

Uploaded by

gmranuj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

Exp 2 SDK Ok

The document provides a comprehensive guide on data visualization techniques in Python using Matplotlib and Seaborn. It includes various examples such as line charts, bar charts, scatter plots, histograms, box plots, facet grids, heat maps, and pair plots, demonstrating how to create each type of visualization with code snippets. Each example is accompanied by a brief description and expected output.

Uploaded by

gmranuj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Practical.

No: 02
Data Visualization in Python
# Python program to demonstrate unary operators in numpy

 Name: _____________________
 Class: S.E (E&TC).
 Roll. No:____________________
Matplotlib-
# Creating Simple plot with matplotlib
Example No:01
import matplotlib.pyplot as plt
import numpy as np
import math #needed for definition of pi
x=np.arange(0, math.pi*2, 0.05)
y=np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()

OUTPUT:
Example No: 2

import matplotlib.pyplot as plt


import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()

OUTPUT:

Line Chart :

Example No: 01

import matplotlib.pyplot as plt


%matplotlib inline
x = [1,2,3,4,5,6,7,8,9,10,11,12]
y1 = [35, 40, 45, 42,55, 45, 50,48,52,60,53,55]
y2 = [15,21,15,18,21, 28, 35, 29,38,35,30,41]
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y1,'ys-') # solid line with yellow colour and square marker
ax.plot(x,y2,'go--') # dash line with green colour and circle marker
ax.legend(labels=( 'Smartphone','tv'), loc='lower right') # legend at lower right
ax.set_title("Monthly Sales")
ax.set_xlabel('month')
ax.set_ylabel('sales')
plt.show()

OUTPUT :

Example No: 02
import matplotlib.pyplot as plt
Year = [1920,1930,1940,1950,1960,1970,1980,1990,2000,2010]
Unemployment_Rate = [9.8,12,8,7.2,6.9,7,6.5,6.2,5.5,6.3]
plt.plot(Year, Unemployment_Rate, color='red', marker='o')
plt.title('Unemployment Rate Vs Year', fontsize=14)
plt.xlabel('Year', fontsize=14)
plt.ylabel('Unemployment Rate', fontsize=14)
plt.grid(True)
plt.show()

OUTPUT:

Bar Chart :
Example No: 01
import matplotlib.pyplot as plt

%matplotlib inline
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])

langs=['C', 'C++', 'Java', 'Python', 'PHP']


students=[23,17,35,29,12]
ax.bar(langs,students)
ax.set_xlabel('Languages')
ax.set_ylabel('Number of Students')
plt.show()

OUTPUT:

Example No: 02

import numpy as np
import matplotlib.pyplot as plt
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30, 'Python':35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(courses, values, color ='maroon', width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()

OUTPUT:

Scatter plot :
Example No: 01

import matplotlib.pyplot as plt

%matplotlib inline

boys_grades = [75, 78, 65, 72, 68, 80, 55, 45, 85, 87,75,77,74,71,85]

roll_no = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15]

fig=plt.figure()
ax=fig.add_axes([0,0,1,1])

ax.scatter(roll_no,boys_grades, color='b')

ax.set_xlabel('Roll Number')

ax.set_ylabel('Grades Scored')

ax.set_title('Scatter plot')

plt.show()

OUTPUT:

Example No: 02
import numpy
import matplotlib.pyplot as plt
x = numpy.random.normal(5.0, 1.0, 1000)
y = numpy.random.normal(10.0, 2.0, 1000)
plt.scatter(x, y)
plt.show()

Histogram :
Example No :01

import matplotlib.pyplot as plt


import numpy as np
%matplotlib inline
x=np.random.normal(170,10,250)
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.hist(x)
ax.set_xlabel('Event')
ax.set_ylabel('Frequency')
ax.set_title('Histogram')
plt.show()

OUTPUT:
Example No : 02
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.show()

OUTPUT:
Bar Plot-
Example No : 01

import numpy as np
import matplotlib.pyplot as plt
data = [[30, 25, 50, 20],
[40, 23, 51, 17],
[35, 22, 45, 19]]
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)

OUTPUT:
Example No :02

import pandas as pd
from matplotlib import pyplot as plt
# Read CSV into pandas
data = pd.read_csv(r"cars.csv")
data.head()
df = pd.DataFrame(data)
name = df['car'].head(12)
price = df['price'].head(12)
# Figure Size
fig = plt.figure(figsize =(10, 7))
# Horizontal Bar Plot
plt.bar(name[0:10], price[0:10])
# Show Plot
plt.show()

OUTPUT:
Box Plot :
Example No :01
# Import libraries
import matplotlib.pyplot as plt
import numpy as np
# Creating dataset
np.random.seed(10)
data = np.random.normal(100, 20, 200)
fig = plt.figure(figsize =(10, 7))
# Creating plot
plt.boxplot(data)
# show plot
plt.show()
OUTPUT:
Example No :02
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))
fig1, ax1 = plt.subplots()
ax1.set_title('Basic Plot')
ax1.boxplot(data)

OUTPUT :
FacetGrid –
Example No : 01
# importing packages
import seaborn
import matplotlib.pyplot as plt
# loading of a dataframe from seaborn
df = seaborn.load_dataset('tips')
# Form a facetgrid using columns with a hue
graph = seaborn.FacetGrid(df, row ='smoker', col ='time')
# map the above form facetgrid with some attributes
graph.map(plt.hist, 'total_bill', bins = 15, color ='orange')
# show the object
plt.show()

OUTPUT:
Example No :02
# importing packages
import seaborn
import matplotlib.pyplot as plt
# loading of a dataframe from seaborn
df = seaborn.load_dataset('tips')
# Form a facetgrid using columns with a hue
graph = seaborn.FacetGrid(df, col ='time', hue ='smoker')
# map the above form facetgrid with some attributes
graph.map(seaborn.regplot, "total_bill", "tip").add_legend()
# show the object
plt.show()

OUTPUT:

Heat Map –
Example No :01
import pandas as
pd import seaborn
as sns
import matplotlib.pyplot as plt
%matplotlib inline
data =
pd.read_csv('attendance.csv',index_col='MONTH')
sns.heatmap(data,annot=True)
plt.title('Monthly Percentage Attendance')
OUTPUT:

Example No :02

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])

fig, ax = plt.subplots()
im = ax.imshow(harvest)
# Show all ticks and label them with the respective list entries
ax.set_xticks(np.arange(len(farmers)), labels=farmers)
ax.set_yticks(np.arange(len(vegetables)), labels=vegetables)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
for i in range(len(vegetables)):
for j in range(len(farmers)):
text = ax.text(j, i, harvest[i, j], ha="center", va="center", color="w")
ax.set_title("Harvest of local farmers (in tons/year)")
fig.tight_layout()
plt.show()

OUTPUT:

Pair Plot –
Example No : 01
# importing the required libraries
import seaborn as sbn
import matplotlib.pyplot as plt
# loading the dataset using the seaborn library
mydata = sbn.load_dataset('penguins')
# pairplot with the hue = gender parameter
sbn.pairplot(mydata, hue = 'gender')
# displaying the plot
plt.show()

OUTPUT:

You might also like