import pandas as pd
import numpy as np
Data Visualization with Matplotlib
In this module we will learn how to visualize data using Matplotlib, a powerful plotting library in Python. We will cover various types of plots including line charts, bar charts, histograms, scatter plots, pie charts, and box plots.
= pd.read_csv('diabetes.csv') df
import matplotlib.pyplot as plt
Line Chart
#Parameter: x, y Coordinates for data points
= [3, 6, 9, 12, 15, 18, 21, 24]
age = [95, 120, 141, 159, 174, 185, 187, 187]
Mike = [99, 126, 145, 163, 179, 191, 191, 191]
George
='blue', linewidth=3, marker='o', markersize=8, linestyle='--')
plt.plot(age, Mike, color
='red', linewidth=3, marker='o', markersize=8, linestyle='--')
plt.plot(age, George, color
"Line Chart")
plt.title('Height (cm)')
plt.ylabel('Age (years)')
plt.xlabel(=('Mike', 'George'))
plt.legend(labels plt.show()
Bar Chart
# This code creates a simple bar chart to show total bills for different days.
# X-axis represents the days and Y-axis shows total bill amount.
= ['Thur', 'Fri', 'Sat', 'Sun']
x = [170, 120, 250, 190]
y
='green', edgecolor='black', linewidth=2)
plt.bar(x, y, color"Bar Chart")
plt.title("Day")
plt.xlabel("Total Bill")
plt.ylabel( plt.show()
Histogram
= df['Pregnancies']
pregnancies
=10, color='steelblue', edgecolor='black',linestyle='--')
plt.hist(pregnancies, bins"Histogram")
plt.title("Number of Pregnancy")
plt.xlabel("Frequency")
plt.ylabel( plt.show()
Scatter Plot
= df['BMI']
BMI = df['BloodPressure']
BloodPressure
= 15)
plt.scatter(BMI, BloodPressure, s "Scatter Plot")
plt.title("BMI")
plt.xlabel("Blood Pressure")
plt.ylabel(
= np.polyfit(BMI, BloodPressure, 1)
b, a
*BMI + a, color='red', linewidth=2)
plt.plot(BMI, b plt.show()
Pie Chart
# This code creates a simple pie chart to visualize distribution of different car brands.
# Each slice of pie represents the proportion of cars for each brand in the dataset.
= ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]
cars = [23, 10, 35, 15, 12]
data = [0.1, 0.5, 0, 0, 0]
explode = ( "orange", "cyan", "yellow","grey", "green")
colors
=cars, explode=explode, colors=colors, autopct='%d%%', shadow = True)
plt.pie(data, labels#plt.title("Pie Chart")
plt.show()
Box Plot
= df['Pregnancies']
Pregnancies = df['Glucose']
Glucose = df['BloodPressure']
BloodPressure = df['SkinThickness']
SkinThickness = df['Age']
Age
= Pregnancies
data
plt.boxplot(data)"Groups")
plt.xlabel("Values")
plt.ylabel("Box Plot")
plt.title( plt.show()