Tip
For π€― inspiration + π©βπ» code, check out the Python Graph Gallery
Basic Setup
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Set style for seaborn (optional)
"whitegrid") sns.set_style(
Creating a Figure and Axes
# Create a new figure and axis
= plt.subplots(figsize=(10, 6))
fig, ax
# Create multiple subplots
= plt.subplots(1, 2, figsize=(12, 5)) fig, (ax1, ax2)
Common Plot Types
Line Plot
= np.linspace(0, 10, 100)
x = np.sin(x)
y ='sin(x)') ax.plot(x, y, label
Scatter Plot
= np.random.rand(50)
x = np.random.rand(50)
y =0.5) plt.scatter(x, y, alpha
Bar Plot
= ['A', 'B', 'C', 'D']
categories = [3, 7, 2, 5]
values plt.bar(categories, values)
Histogram
= np.random.randn(1000)
data =30, edgecolor='black') ax.hist(data, bins
Customizing Plots
Labels and Title
'X-axis label')
ax.set_xlabel('Y-axis label')
ax.set_ylabel('Plot Title') ax.set_title(
Legend
ax.legend()
Axis Limits
0, 10)
ax.set_xlim(-1, 1) ax.set_ylim(
Grid
True, linestyle='--', alpha=0.7) ax.grid(
Ticks
0, 2, 4, 6, 8, 10])
ax.set_xticks([-1, -0.5, 0, 0.5, 1]) ax.set_yticks([
Color and Style
Changing Colors
='r') # 'r' for red
ax.plot(x, y, color='blue') ax.scatter(x, y, c
Line Styles
='--') # dashed line
ax.plot(x, y, linestyle=':') # dotted line ax.plot(x, y, ls
Marker Styles
='o') # circles
ax.plot(x, y, marker='s') # squares ax.plot(x, y, marker
Saving and Displaying
Saving the Figure
'my_plot.png', dpi=300, bbox_inches='tight') plt.savefig(
Displaying the Plot
plt.show()
Useful Tips for Seaborn Users
Use
plt.subplots()
to create custom layouts that Seaborn doesnβt provide.Access the underlying Matplotlib
Axes
object in Seaborn plots:= sns.scatterplot(x='x', y='y', data=df) g 'Custom X Label') g.set_xlabel(
Combine Seaborn and Matplotlib in the same figure:
= plt.subplots() fig, ax ='x', y='y', data=df, ax=ax) sns.scatterplot(x='r', linestyle='--') ax.plot(x, y, color
Use Matplotlibβs
plt.tight_layout()
to automatically adjust subplot parameters for better spacing.
Remember, most Seaborn functions return a Matplotlib Axes
object, allowing you to further customize your plots using Matplotlib functions.