How to Use plt.style.use in Matplotlib for Plot Styling
Use
plt.style.use('style_name') to apply a predefined style to your matplotlib plots. This changes the look of all plots created after the call, making it easy to customize plot appearance consistently.Syntax
The syntax for using plt.style.use is simple:
plt.style.use(style): Applies the style specified bystyle.stylecan be a string naming a built-in style, a path to a style file, or a list of styles to combine.
python
import matplotlib.pyplot as plt plt.style.use('style_name')
Example
This example shows how to use plt.style.use to apply the 'ggplot' style to a simple line plot. The style changes colors, grid, and fonts automatically.
python
import matplotlib.pyplot as plt import numpy as np plt.style.use('ggplot') # Apply ggplot style x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y, label='sin(x)') plt.title('Plot with ggplot style') plt.xlabel('x') plt.ylabel('sin(x)') plt.legend() plt.show()
Output
A line plot with a light red grid background, thicker lines, and styled fonts typical of ggplot.
Common Pitfalls
Common mistakes when using plt.style.use include:
- Calling
plt.style.useafter creating plots, which won't affect existing plots. - Using a style name that does not exist, causing an error.
- Not importing
matplotlib.pyplotaspltbefore using the style.
Always call plt.style.use before plotting to ensure the style applies.
python
import matplotlib.pyplot as plt # Wrong: style applied after plotting plt.plot([1, 2, 3], [4, 5, 6]) plt.style.use('seaborn') # This won't affect the above plot plt.show() # Right: style applied before plotting plt.style.use('seaborn') plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Output
First plot uses default style; second plot uses seaborn style with different colors and grid.
Quick Reference
Here is a quick reference for using plt.style.use:
| Parameter | Description | Example |
|---|---|---|
| style | Name of a built-in style or path to a style file | 'ggplot', 'seaborn', 'bmh' |
| list of styles | Combine multiple styles by passing a list | ['dark_background', 'ggplot'] |
| Usage position | Call before plotting to apply style | plt.style.use('seaborn') |
Key Takeaways
Call plt.style.use('style_name') before creating plots to apply the style.
You can use built-in style names like 'ggplot', 'seaborn', or custom style files.
Combining multiple styles is possible by passing a list of style names.
Using an invalid style name will cause an error, so check available styles with plt.style.available.
Styles help make your plots visually consistent and easier to read.