How to Use Seaborn Style in Matplotlib for Better Plots
You can use
seaborn styles in matplotlib by importing seaborn and calling seaborn.set() before plotting. This changes the default look of matplotlib plots to the nicer Seaborn style automatically.Syntax
To use Seaborn style in Matplotlib, first import Seaborn and then call seaborn.set(). This sets the style globally for all Matplotlib plots.
You can also specify a particular style like darkgrid by passing it as an argument to seaborn.set_style().
python
import seaborn as sns sns.set() # Apply default seaborn style # Or specify a style sns.set_style('darkgrid')
Example
This example shows how to apply Seaborn style to a simple Matplotlib line plot. The style makes the plot look cleaner and more modern.
python
import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set() # Apply seaborn style x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.title('Sine Wave with Seaborn Style') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show()
Output
A line plot of a sine wave with a light grid background and smooth lines styled by seaborn.
Common Pitfalls
- Not calling
seaborn.set()before plotting will keep the default Matplotlib style. - Calling
plt.style.use('seaborn')is an older way; usingseaborn.set()is recommended. - Seaborn styles affect global Matplotlib settings, so reset styles if mixing with other styles.
python
import matplotlib.pyplot as plt import seaborn as sns import numpy as np x = np.linspace(0, 10, 100) y = np.cos(x) # Wrong: style not set before plotting plt.plot(x, y) plt.title('Cosine Wave without Seaborn Style') plt.show() # Right: set seaborn style before plotting sns.set() plt.plot(x, y) plt.title('Cosine Wave with Seaborn Style') plt.show()
Output
First plot: default Matplotlib style without grid.
Second plot: styled with seaborn, showing grid and nicer colors.
Quick Reference
Here is a quick summary of how to use Seaborn styles with Matplotlib:
| Action | Code Example | Effect |
|---|---|---|
| Import Seaborn | import seaborn as sns | Access seaborn styling functions |
| Set default style | sns.set() | Apply seaborn style globally |
| Set specific style | sns.set_style('darkgrid') | Apply a named seaborn style |
| Reset style | sns.reset_orig() | Return to default Matplotlib style |
Key Takeaways
Call seaborn.set() before plotting to apply seaborn style to matplotlib plots.
Seaborn styles improve plot appearance with grids, colors, and fonts.
Set styles globally; changes affect all subsequent matplotlib plots.
Use sns.set_style() to choose specific seaborn styles like 'darkgrid' or 'white'.
Reset styles with sns.reset_orig() if you want to revert to default matplotlib look.