UNIT-IV - Matplotlib
UNIT-IV - Matplotlib
Matplotlib is a popular Python library used for creating static, animated, and interactive
visualizations in python.
It provides a comprehensive set of tools for creating high-quality 2D and 3D plots, charts,
and graphs.
It also offers customization options, and integration with other libraries like NumPy and
Pandas.
Key Features:
Plotting: Line plots, scatter plots, histograms, bar charts, pie charts, and more.
Customization: Control over colors, fonts, labels, titles, axes, and more.
Output: Save plots to files (PNG, PDF, EPS, SVG) or display interactively.
Integration: Works well with other popular libraries like NumPy, Pandas, and Scikit-
learn.
# Data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
# Create plot
plt.plot(x, y)
# Display plot
plt.show()
OUTPUT:
plt.plot(x, y)
plt.show()
plt.scatter(x, y)
plt.show()
3. Bar Chart: Suitable for comparing discrete categories.
categories = ["A", "B", "C"]
values = [5, 7, 3]
plt.bar(categories, values)
plt.show()
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
plt.hist(data, bins=5)
plt.show()
Customizing Plots
Saving Figures
plt.savefig("plot.png")
Advanced Features
# Sample data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 9, 16, 25])
# Add annotations
for i in range(len(x)):
plt.annotate(f"({x[i]}, {y[i]})", (x[i], y[i]), textcoords="offset points",
xytext=(0,10), ha='center')
plt.show()
Note:-
f"({x[i]}, {y[i]})"
- This is an f-string (formatted string literal) shows the coordinates of the point in the
format (x, y).
(x[i], y[i])
- This specifies the (x, y) coordinate of the point where you want the annotation to
appear.
(x[i], y[i])
- This specifies the (x, y) coordinate of the point where you want the annotation to
appear.
xytext=(0, 10)
- This specifies the offset for the annotation text in points, relative to the specified data
point (x[i], y[i]).
(0, 10) means the text will be positioned 0 points horizontally (no shift left or right)
and 10 points vertically above the point.
This offset helps prevent the annotation text from overlapping directly on the point,
making it more readable.
ha='center'
This controls the horizontal alignment of the annotation text relative to its position.
'center' means the annotation text will be centered horizontally above the point.
OUTPUT
Example of Bar Chart
import matplotlib.pyplot as plt
# Sample data
x = ["Apples", "Bananas", "Cherries", "Dates"]
y = [10, 15, 7, 12]
OUTPUT
Example of HISTOGRAM
# bins=5: This specifies the number of bins (intervals) to use for the histogram. In this case,
the data will be divided into 5 equal-width bins.
subplot
A subplot in Matplotlib allows you to create multiple plots (axes) in a single figure, enabling
you to visualize different datasets or aspects of a dataset side-by-side. This is especially useful
when comparing multiple charts or examining various facets of data in one view.
The plt.subplot() function creates a subplot within a grid of a specified number of rows and
columns. The syntax is as follows:
For example, plt.subplot(2, 2, 1) will create a 2x2 grid of subplots and place the plot in the
first (top-left) position.
Example: Creating a 2x2 Grid of Subplots
Here’s how to create four subplots in a 2x2 grid, each with its own data and title:
# Sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [25, 16, 9, 4, 1]
y3 = [1, 2, 3, 4, 5]
y4 = [5, 4, 3, 2, 1]
OUTPUT
Explanation of Code
plt.subplot(2, 2, 1): This creates a 2x2 grid and places the first plot in the top-left
position.
plt.plot(x, y1): Plots the data for the first subplot.
plt.title("y = x^2"): Sets the title for the first subplot.
plt.tight_layout(): Automatically adjusts the spacing between subplots to prevent
overlapping labels and titles.
Matplotlib also provides a more flexible method, plt.subplots(), which creates a grid and
returns a figure and an array of axes objects, making it easier to loop over subplots or access
them individually.
plt.tight_layout()
plt.show()
Summary