Matplotlib
Styles and Themes
Apply built-in styles and customize rcParams.
By EZ4Code Team
stylesthemercparams
Code
import matplotlib.pyplot as plt
import numpy as np
# List available styles
print(plt.style.available[:5])
# Apply a style context temporarily
with plt.style.context("ggplot"):
x = np.linspace(0, 1, 50)
plt.plot(x, x ** 2, label="x^2")
plt.plot(x, np.sqrt(x), label="sqrt")
plt.legend()
plt.show()
# Global rcParams customization
plt.rcParams.update({
"figure.figsize": (8, 4),
"font.size": 12,
"axes.grid": True,
"lines.linewidth": 2,
})Explanation
plt.style.use applies a look globally, while style.context applies it only inside a with-block. rcParams holds hundreds of defaults for figure size, fonts, grid, and line styling that persist until changed. Available built-in styles include ggplot, seaborn-v0_8, and bmh.
More Matplotlib Snippets
Line Plot
Plot lines with markers, colors, and styles.
Bar Chart
Draw vertical, horizontal, and grouped bars.
Scatter Plot
Visualize relationships with size and color encodings.
Subplots
Arrange multiple axes with subplots and GridSpec.
Labels and Legend
Annotate plots with text, arrows, and legend options.
Save Figure
Export figures to PNG, PDF, and SVG with DPI control.