Introduction to Matplotlib
- This module introduces the basics of Matplotlib in Python. You will learn how to install Matplotlib, import matplotlib.pyplot, create simple plots, add titles and labels, enable grids, and adjust figure size for better data visualization.
Installing Matplotlib
If not installed, use:
pip install matplotlib
In Jupyter Notebook:
!pip install matplotlib
Importing Matplotlib
import matplotlib.pyplot as plt
Explanation:
matplotlib is the library.
pyplot is a module used for plotting.
plt is an alias for easier use.
Basic Plot Structure
A simple line plot:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.show()
Explanation:
plt.plot() creates the plot.
plt.show() displays the output.
Adding Title and Labels
plt.plot(x, y)
plt.title("Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
Why Important?
Titles and labels make charts understandable and professional.
Grid and Figure Size
Adding Grid:
plt.plot(x, y)
plt.grid(True)
plt.show()
- Setting Figure Size:
plt.figure(figsize=(6,4))
plt.plot(x, y)
plt.show()
figsize=(width, height) controls chart size.