Matplotlib
Matplotlib is a plotting library that allows you to create static, animated, and interactive visualizations. It
works well with NumPy and Pandas to plot data efficiently.
1. IMPORT MATPLOTLIB
Import matplotlib as plt.
2. Basic Plotting: Line Plot
A line plot is the simplest type of plot and is great for visualizing trends in data.
Example: Line Plot
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# Create a line plot
plt.plot(x, y)
# Add title and labels
plt.title('Basic Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the plot
plt.show()
plt.plot(x, y): Plots the x values on the x-axis and y values on the y-axis.
plt.title(): Adds a title to the plot.
plt.xlabel() and plt.ylabel(): Label the axes.
3. Plotting Multiple Lines
You can plot multiple lines on the same graph.
Example: Multiple Line Plot
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]
plt.plot(x, y1, label='y = x^2', color='blue')
plt.plot(x, y2, label='y = x', color='green')
plt.title('Multiple Lines')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend() # Show legend
plt.show()
plt.plot(): You can specify label for each line and use different colors.
plt.legend(): Displays the legend to distinguish between multiple lines.
4. Scatter Plot
Scatter plots are useful for visualizing the relationship between two variables.
Example: Scatter Plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.scatter(x, y, color='red', label='Data points')
plt.title('Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.show()
plt.scatter(x, y): Plots x and y as discrete points.
You can also set the color of the points using the color argument.
5. Bar Chart
Bar charts are ideal for comparing quantities across different categories.
Example: Bar Chart
categories = ['A', 'B', 'C', 'D']
values = [10, 15, 7, 25]
plt.bar(categories, values, color='orange')
plt.title('Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
plt.bar(categories, values): Creates a bar chart with the given categories and
values.
6. Histogram
Histograms are used to visualize the distribution of a dataset.
Example: Histogram
import numpy as np
data = np.random.randn(1000) # Generate 1000 random data points
plt.hist(data, bins=30, color='purple', edgecolor='black')
plt.title('Histogram')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()
plt.hist(data, bins): Plots a histogram of the data with a specified number of bins
(intervals).
You can also customize the color and edges of the bars.
7. Pie Chart
Pie charts are great for showing proportions of a whole.
Example: Pie Chart
labels = ['A', 'B', 'C', 'D']
sizes = [10, 20, 30, 40]
colors = ['red', 'green', 'blue', 'yellow']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart')
plt.show()
plt.pie(): Creates a pie chart where you can specify the labels, colors, and other
parameters.
autopct: Displays the percentage on each slice.
startangle: Rotates the start angle for better visualization.
8. Subplots
You can create multiple plots in the same figure using subplots.
Example: Subplots
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig, axs = plt.subplots(2, 1) # Create 2 rows and 1 column of subplots
# Plot in first subplot
axs[0].plot(x, y)
axs[0].set_title('Line Plot')
# Plot in second subplot
axs[1].scatter(x, y)
axs[1].set_title('Scatter Plot')
plt.tight_layout() # Adjust layout to prevent overlapping
plt.show()
plt.subplots(): Creates a grid of subplots. In this case, 2 rows and 1 column.
axs[index]: Accesses each subplot to customize it individually.
9. Customization and Styles
You can customize your plots in various ways, like changing line styles, colors, and adding grid
lines.
Example: Customizing a Plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y, linestyle='--', color='red', marker='o', markersize=8)
plt.title('Customized Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True) # Add gridlines
plt.show()
linestyle: Specifies the line style (e.g., solid, dashed).
color: Sets the color of the line.
marker: Adds a marker for each data point (e.g., 'o' for circles).
markersize: Adjusts the size of the markers.
grid(True): Adds gridlines to the plot.
10. Saving Plots
Once you're happy with your plot, you can save it to a file.
Example: Save a Plot
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y)
plt.title('Save this Plot')
# Save the plot as a PNG file
plt.savefig('my_plot.png')
plt.show()
plt.savefig('filename.png'): Saves the plot to the specified file.