Matplotlib Complete Notes with Examples
What is Matplotlib?
Matplotlib is a Python library used for creating static, animated, and interactive visualizations. It is widely used
for data visualization and works well with other libraries like NumPy and Pandas.
Installation
Install it using pip:
pip install matplotlib
Importing Pyplot
You generally import matplotlib's pyplot module like this:
import matplotlib.pyplot as plt
Common Plot Types
- Line Plot: plt.plot()
- Bar Chart: plt.bar()
- Scatter Plot: plt.scatter()
- Histogram: plt.hist()
- Pie Chart: plt.pie()
Basic Line Plot Example
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Matplotlib Complete Notes with Examples
Customization Options
- Title: plt.title("Title")
- Axis Labels: plt.xlabel("X"), plt.ylabel("Y")
- Grid: plt.grid(True)
- Legend: plt.legend()
- Line styles, markers, and colors can be customized.
Subplots and Multiple Lines
Use plt.subplot(rows, cols, index) to create subplots. For multiple lines:
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
plt.legend()
Saving Plots
You can save plots to a file using:
plt.savefig("filename.png")
Pie Chart Example
labels = ['Rent', 'Food', 'Utilities']
sizes = [40, 35, 25]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Expenses")
plt.axis('equal')
plt.show()
Bar + Line Combo Example
Use twinx() to combine bar and line plots:
fig, ax1 = plt.subplots()
ax1.bar(months, sales)
Matplotlib Complete Notes with Examples
ax2 = ax1.twinx()
ax2.plot(months, growth)
Interactive Plot (with Plotly)
Install Plotly: pip install plotly
import plotly.express as px
fig = px.line(df, x='Month', y='Sales')
fig.show()