Matplotlib Visualization Techniques and Customization
Coordinate System and Grid Customization
Configure axes, grids, titles, and labels.
import numpy as np
import matplotlib.pyplot as plt
# Generate data points
time_points = np.linspace(0, 2 * np.pi, 200)
wave_amplitude = np.sin(time_points)
# Initialize figure and axis
fig, ax = plt.subplots(figsize=(10, 6))
# Plot the sine wave
ax.plot(time_points, wave_amplitude, label='Sine Wave')
# Configure grid
ax.grid(True, linestyle='-.', color='teal', alpha=0.6)
# Set axis limits
ax.set_xlim(0, 7)
ax.set_ylim(-1.5, 1.5)
# Customize ticks
ax.set_yticks([-1, 0, 1])
ax.set_yticklabels(['Min', 'Zero', 'Max'])
ax.set_xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
# Label axes
ax.set_xlabel('Time (radians)', fontsize=12)
ax.set_ylabel('Amplitude', fontsize=12, rotation=0, labelpad=20)
# Add title
ax.set_title('Sine Wave Demonstration', fontsize=14, fontfamily='serif')
plt.show()
Legend Configuraton
Add and customize legends for multiple plots.
import numpy as np
import matplotlib.pyplot as plt
x_vals = np.linspace(0, 2 * np.pi, 50)
y_sin = np.sin(x_vals)
y_cos = np.cos(x_vals)
fig, ax = plt.subplots()
ax.plot(x_vals, y_sin, label='Sine')
ax.plot(x_vals, y_cos, label='Cosine')
ax.legend(loc='upper right', frameon=True, shadow=True, fontsize=10)
plt.show()
Spine Adjustment
Control the visibility and position of plot spines.
import matplotlib.pyplot as plt
import numpy as np
x_data = np.linspace(0, 10, 100)
y_data = np.sin(x_data)
fig, ax = plt.subplots()
ax.plot(x_data, y_data)
# Hide top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# Move bottom spine to y=0 and left spine to x=0
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
plt.show()
Saving Figures
Save plots with custom properties.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8, 6))
ax.set_facecolor('#f0f0f0') # Inner background
x = np.linspace(0, 10, 100)
y = np.cos(x)
ax.plot(x, y, color='purple')
plt.savefig('cosine_plot.png',
dpi=150,
facecolor='skyblue', # Outer background
edgecolor='black',
bbox_inches='tight')
Line Styling
Customize line appearance with markers and styles.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 50)
y = np.sin(x)
plt.plot(x, y,
color='#FF5733',
linestyle=':',
marker='d',
markersize=6,
markerfacecolor='yellow',
markeredgewidth=1.5,
markeredgecolor='black',
alpha=0.8)
plt.show()
Multiple Subplots
Arrange multiple plots in a grid.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 50)
y = np.sin(x)
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, np.cos(x))
plt.subplot(2, 1, 2)
plt.plot(x, np.tan(x))
plt.tight_layout()
plt.show()
Inset Plots
Embed smaller plots with in a larger figure.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(8, 6))
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
# Main plot
ax_main = fig.add_subplot(111)
ax_main.plot(x, y, 'b-')
# Inset plot
ax_inset = fig.add_axes([0.6, 0.6, 0.25, 0.25])
ax_inset.plot(x, y, 'r--')
ax_inset.set_title('Inset View')
plt.show()
Complex Layouts with GridSpec
Create non-uniform subplot layouts.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
gs = gridspec.GridSpec(3, 3)
fig = plt.figure(figsize=(10, 8))
ax1 = fig.add_subplot(gs[0, :])
ax1.plot(x, np.sin(x))
ax2 = fig.add_subplot(gs[1, :-1])
ax2.plot(x, np.cos(x))
ax3 = fig.add_subplot(gs[1:, -1])
ax3.plot(x, np.tan(x))
plt.tight_layout()
plt.show()
Dual-Axis Plots
Plot data with two different y-axes.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.exp(x / 3)
y2 = np.log(x + 1)
fig, ax1 = plt.subplots()
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Exponential', color='tab:red')
ax1.plot(x, y1, color='tab:red')
ax1.tick_params(axis='y', labelcolor='tab:red')
ax2 = ax1.twinx()
ax2.set_ylabel('Logarithmic', color='tab:blue')
ax2.plot(x, y2, color='tab:blue')
ax2.tick_params(axis='y', labelcolor='tab:blue')
plt.show()
Text and Annotations
Add text and arrows to highlight features.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
# Add text
ax.text(1.5, 0.5, r'$y=\sin(x)$', fontsize=14, color='green')
# Add annotation with arrow
ax.annotate('Peak', xy=(np.pi/2, 1), xytext=(np.pi/2, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05, headwidth=8))
plt.show()
Bar Charts
Create basic and stacked bar charts.
import matplotlib.pyplot as plt
import numpy as np
categories = ['A', 'B', 'C', 'D']
values1 = np.random.randint(10, 50, size=4)
values2 = np.random.randint(10, 50, size=4)
x = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, values1, width, label='Group 1')
rects2 = ax.bar(x + width/2, values2, width, label='Group 2')
ax.set_ylabel('Scores')
ax.set_title('Scores by Group')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
plt.show()
Histograms and Box Plots
Visualize distributions and statistical summaries.
import matplotlib.pyplot as plt
import numpy as np
# Histogram
data = np.random.randn(1000)
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
plt.title('Histogram of Random Data')
# Box plot
fig, ax = plt.subplots()
data_box = [np.random.normal(0, std, 100) for std in range(1, 4)]
ax.boxplot(data_box, vert=True, patch_artist=True)
ax.set_title('Box Plot')
plt.show()
Scatter Plots
Plot relationships between variables with varying point sizes and colors.
import matplotlib.pyplot as plt
import numpy as np
n = 100
x = np.random.rand(n)
y = np.random.rand(n)
colors = np.random.rand(n)
sizes = 1000 * np.random.rand(n)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.show()
Pie Charts
Create customized pie charts.
import matplotlib.pyplot as plt
import numpy as np
labels = ['Apple', 'Banana', 'Orange']
sizes = [45, 30, 25]
explode = (0, 0.1, 0) # Highlight Banana
fig, ax = plt.subplots()
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90, colors=['#ff9999','#66b3ff','#99ff99'])
ax.axis('equal') # Equal aspect ratio ensures pie is circular.
plt.show()
Heatmaps
Display matrix data as a color-coded image.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
plt.imshow(data, cmap='hot', interpolation='nearest')
plt.colorbar()
# Add text annotations
for i in range(10):
for j in range(10):
plt.text(j, i, f'{data[i, j]:.2f}', ha='center', va='center', color='blue')
plt.show()
Area Plots
Stacked area chart for composition over time.
import matplotlib.pyplot as plt
import numpy as np
days = np.arange(1, 6)
sleep = [7, 8, 6, 11, 7]
eat = [2, 3, 4, 3, 2]
work = [7, 8, 7, 2, 2]
play = [8, 5, 7, 8, 13]
plt.stackplot(days, sleep, eat, work, play, labels=['Sleep', 'Eat', 'Work', 'Play'])
plt.legend(loc='upper left')
plt.xlabel('Day')
plt.ylabel('Hours')
plt.show()
Radar Charts
Plot multiavriate data on a polar coordinate system.
import matplotlib.pyplot as plt
import numpy as np
labels = np.array(['Speed', 'Reliability', 'Comfort', 'Safety', 'Efficiency'])
stats = np.array([90, 60, 85, 70, 80])
angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False).tolist()
stats = np.concatenate((stats, [stats[0]]))
angles += angles[:1]
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
ax.plot(angles, stats, color='blue', linewidth=2)
ax.fill(angles, stats, color='blue', alpha=0.25)
ax.set_yticklabels([])
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
plt.show()
3D Surface Plots
Visualize data in three dimensions.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()