Visualize data like a pro! Full Matplotlib course with core and advanced plotting, customizations, theory, and real Python code, by Ram Sir.
Start Learning MatplotlibRam Sir, Python visualization expert: 2+ years of teaching Matplotlib and data storytelling for analytics, research, and business.
Matplotlib's core: create and display simple plots.
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [10,20,25,30]
plt.plot(x, y) # Line
plt.scatter(x, y) # Scatter
plt.bar(x, y) # Bar
plt.show()
import numpy as np
data = np.random.randn(200)
plt.hist(data, bins=20)
sizes = [15, 30, 45, 10]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show()
fig, ax = plt.subplots()
ax.plot([0,1,2],[3,1,4])
ax.set_title("Using OO API")
plt.show()
Use pyplot for fast plots, and the OO API (fig, ax) for advanced control.
Make your plots beautiful and informative!
plt.plot([1,2,3],[4,5,6], label="My Data")
plt.title("Plot Title")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.legend()
plt.show()
plt.plot(x, y, color='red', linewidth=2, marker='o')
plt.xticks([1,2,3,4], ['One','Two','Three','Four'])
plt.yticks(np.arange(10,31,5))
plt.grid(True, linestyle="--")
plt.show()
plt.style.use('ggplot')
plt.plot([1,2,3],[4,5,6])
plt.show()
Try built-in styles: plt.style.available. Use color maps for heatmaps and imshow.
Beyond the basics: subplots, annotations, 3D, and more.
fig, axs = plt.subplots(2, 2)
axs[0,0].plot(x, y)
axs[1,1].bar(x, y)
plt.tight_layout()
plt.show()
plt.plot(x, y)
plt.annotate('Max', xy=(4,30), xytext=(3,28),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.text(2, 20, 'Hello!', fontsize=12, color='green')
plt.show()
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot([1,2,3],[4,5,6],[7,8,9])
plt.show()
theta = np.linspace(0, 2*np.pi, 100)
r = np.abs(np.sin(theta))
plt.polar(theta, r)
plt.show()
img = np.random.rand(10,10)
plt.imshow(img, cmap='viridis')
plt.colorbar()
plt.show()
Use subplot2grid, gridspec for complex layouts. imshow for images and heatmaps.
Save figures, export to various formats, and interact with plots.
plt.plot(x, y)
plt.savefig('plot.png') # PNG
plt.savefig('plot.pdf') # PDF
plt.savefig('plot.svg', dpi=300) # SVG, high-res
plt.show()
plt.ion() # Interactive mode on
plt.plot(x, y)
plt.pause(2) # Show for 2 seconds
plt.ioff() # Interactive mode off
plt.show()
# In Jupyter
%matplotlib inline
# In PyQt5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
Use plt.savefig() before plt.show(). For web/GUI, check Matplotlib's backends.
Go further with performance, Seaborn, Pandas, and animations!
# Use LineCollection for many lines
from matplotlib.collections import LineCollection
# Downsample data before plotting large datasets
import seaborn as sns
sns.set_theme()
sns.scatterplot(x='col1', y='col2', data=df)
df.plot(kind='hist')
plt.show()
import matplotlib.animation as animation
fig, ax = plt.subplots()
line, = ax.plot([], [])
def update(frame):
line.set_data([0, frame], [0, frame**2])
return line,
ani = animation.FuncAnimation(fig, update, frames=10)
plt.show()
Combine Matplotlib with Seaborn for stats, Pandas for DataFrames, and animations for dynamic presentations.
Image output (simulated)
Most-used Matplotlib functions and features, with code examples:
plt.plot(x, y)
plt.scatter(x, y)
plt.title("My Title")
plt.legend()
fig, axs = plt.subplots(2,2)
axs[0,0].plot(x, y)
plt.imshow(data, cmap='hot')
plt.colorbar()
plt.savefig("out.png")
plt.savefig("out.svg")
import seaborn as sns
sns.heatmap(df)