UNIT – 4 : Introduction to Matplotlib:
Installing Matplotlib
If you haven’t installed Matplotlib yet, you can do so using:
Code:
pip install matplotlib
Basic Usage
Import Matplotlib and create a simple plot:
Code:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 50]
plt.plot(x, y) # Line chart
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Line Chart")
plt.show()
2. Line Chart
Example: Simple Line Chart
Code:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [5, 15, 10, 25, 30]
plt.plot(x, y, marker='o', linestyle='-', color='b', label="Sales")
plt.xlabel("Months")
plt.ylabel("Revenue")
plt.title("Monthly Revenue")
plt.legend()
plt.grid(True)
plt.show()
Explanation:
• marker='o' adds circular markers at data points.
• linestyle='-' creates a solid line.
• color='b' sets the line color to blue.
• plt.legend() adds a legend.
• plt.grid(True) enables grid lines.
3. Bar Chart
Example: Vertical and Horizontal Bar Chart
Code:
import matplotlib.pyplot as plt
categories = ["A", "B", "C", "D"]
values = [40, 70, 30, 85]
# Vertical bar chart
plt.bar(categories, values, color='skyblue', label="Scores")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart Example")
plt.legend()
plt.show()
# Horizontal bar chart
plt.barh(categories, values, color='orange', label="Scores")
plt.xlabel("Values")
plt.ylabel("Categories")
plt.title("Horizontal Bar Chart")
plt.legend()
plt.show()
Explanation:
• plt.bar() creates a vertical bar chart.
• plt.barh() creates a horizontal bar chart.
4. Scatter Plot
Example: Scatter Plot with Customization
Code:
import matplotlib.pyplot as plt
x = [10, 20, 30, 40, 50]
y = [5, 15, 10, 25, 30]
plt.scatter(x, y, color='red', marker='s', s=100, label="Data Points")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Scatter Plot Example")
plt.legend()
plt.show()
Explanation:
• plt.scatter() creates a scatter plot.
• color='red' sets the dot color.
• marker='s' makes square markers.
• s=100 changes marker size.
5. Histogram
Example: Visualizing Data Distribution
Code:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(1000) # Generates 1000 random numbers
plt.hist(data, bins=30, color='purple', edgecolor='black')
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram Example")
plt.show()
Explanation:
• plt.hist(data, bins=30) creates a histogram with 30 bins.
• edgecolor='black' adds black borders to bins.
6. Pie Chart
Example: Simple Pie Chart
Code:
import matplotlib.pyplot as plt
labels = ["Apple", "Banana", "Cherry", "Grapes"]
sizes = [20, 30, 25, 25]
colors = ['red', 'yellow', 'pink', 'purple']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
plt.title("Fruit Distribution")
plt.show()
Explanation:
• labels defines category names.
• autopct='%1.1f%%' shows percentages.
• startangle=140 rotates the chart.
7. Box Plot
Example: Showing Data Distribution & Outliers
Code:
import matplotlib.pyplot as plt
import numpy as np
data = [np.random.randint(10, 50, 10), np.random.randint(30, 70, 10), np.random.randint(20, 60,
10)]
plt.boxplot(data, labels=["Group A", "Group B", "Group C"])
plt.title("Box Plot Example")
plt.show()
Explanation:
• Box plots show medians, quartiles, and outliers.
8. Heatmap (Using Seaborn)
Code:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
data = np.random.rand(5, 5) # 5x5 random data matrix
sns.heatmap(data, cmap='coolwarm', annot=True)
plt.title("Heatmap Example")
plt.show()
Explanation:
• sns.heatmap() generates a heatmap.
• cmap='coolwarm' sets the color map.
• annot=True shows values inside the heatmap.
9. Multiple Subplots
Code:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 25, 30, 50]
y2 = [5, 15, 10, 25, 30]
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].plot(x, y1, color='b', label="Line 1")
ax[0].set_title("Line Chart")
ax[1].bar(x, y2, color='r', label="Bar Chart")
ax[1].set_title("Bar Chart")
plt.show()
Explanation:
• plt.subplots(1, 2) creates two side-by-side plots.
• ax[0] is the first subplot.
• ax[1] is the second subplot.
10. Customizing Plots
Example: Changing Style
Code:
import matplotlib.pyplot as plt
plt.style.use('ggplot') # Applying a style
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 50]
plt.plot(x, y, marker='o', linestyle='--', color='g', label="Sales")
plt.xlabel("Months")
plt.ylabel("Revenue")
plt.title("Styled Line Chart")
plt.legend()
plt.show()
Explanation:
• plt.style.use('ggplot') applies a predefined style.