Data Visualization using Matplotlib -
Class 12 CBSE Notes
1. Introduction to Data Visualization
Data visualization is the graphical representation of data and information using visual
elements like charts, graphs, and plots.
Importance:
- Helps in analyzing data trends and patterns.
- Makes data interpretation easier.
- Enhances decision-making based on visual insights.
2. Matplotlib Library
Importing Matplotlib:
import matplotlib.pyplot as plt
3. Types of Plots
A. Line Plot
Used to represent continuous data over intervals like time, distance, etc.
Example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y, color='blue', marker='o', linestyle='--')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('Simple Line Plot')
plt.grid(True)
plt.show()
B. Bar Graph
Used to compare data across different categories.
Example:
subjects = ['IP', 'Math', 'English', 'Physics']
marks = [88, 92, 85, 90]
plt.bar(subjects, marks, color='purple')
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.title("Marks in Different Subjects")
plt.show()
C. Histogram
Used to show frequency distribution of continuous data (e.g. age, scores).
Example:
ages = [15, 16, 16, 17, 18, 15, 16, 17, 17, 16, 18]
plt.hist(ages, bins=4, color='orange', edgecolor='black')
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.title("Age Distribution of Students")
plt.show()
4. Plot Customization
import pandas as pd
import matplotlib.pyplot as plt
# Sample plot data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, label='Line Plot')
# Add labels and title
plt.xlabel('X-Axis Label') # X-axis label
plt.ylabel('Y-Axis Label') # Y-axis label
plt.title('Title of the Graph') # Graph title
# Add legend and grid
plt.legend() # Legend
plt.grid(True) # Grid
plt.show() #show the plot
5. Saving a Plot
plt.savefig('plot.png')
6. Complete Example
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 25, 30, 35]
y2 = [5, 15, 20, 25, 30]
plt.plot(x, y1, label='Line A', color='green', marker='o', linestyle='--')
plt.plot(x, y2, label='Line B', color='red', marker='s', linestyle='-.')
plt.xlabel('Time')
plt.ylabel('Values')
plt.title('Multiple Line Plot')
plt.legend()
plt.grid(True)
plt.show()
7. Summary Table
Feature Function Example
Line Plot plt.plot() plt.plot(x, y)
Bar Graph plt.bar() plt.bar(x, height)
Histogram plt.hist() plt.hist(data, bins=5)
Title plt.title() plt.title("My Plot")
Axis Labels plt.xlabel(), plt.ylabel() plt.xlabel("X")
Grid plt.grid(True)
Legend plt.legend()
Save Plot plt.savefig("file.png")