4 min read min read
Introduction to Matplotlib
Learn the basics of creating charts in Python
Introduction to Matplotlib
What is Matplotlib?
Matplotlib is Python's most popular charting library. It creates:
- Line charts
- Bar charts
- Scatter plots
- Histograms
- And many more!
Install Matplotlib
terminal
pip install matplotlibYour First Chart
code.py
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create chart
plt.plot(x, y)
# Show it
plt.show()This creates a simple line chart!
Add Title and Labels
code.py
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.title('My First Chart')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.show()Save Chart to File
code.py
plt.plot(x, y)
plt.title('My Chart')
plt.savefig('my_chart.png')Saves as PNG image file.
Basic Chart Types
code.py
import matplotlib.pyplot as plt
# Line chart
plt.plot([1, 2, 3], [1, 4, 9])
# Bar chart
plt.bar(['A', 'B', 'C'], [10, 20, 15])
# Scatter plot
plt.scatter([1, 2, 3], [1, 4, 9])The plt Pattern
Most matplotlib code follows this pattern:
code.py
import matplotlib.pyplot as plt
# 1. Create the chart
plt.plot(data)
# 2. Customize it
plt.title('Title')
plt.xlabel('X')
plt.ylabel('Y')
# 3. Show or save it
plt.show()Key Points
- import matplotlib.pyplot as plt is standard
- plt.plot() creates line charts
- plt.bar() creates bar charts
- plt.scatter() creates scatter plots
- plt.show() displays the chart
- plt.savefig() saves to file
What's Next?
Learn about Figure and Axes - the building blocks of matplotlib charts.