Style Plots using Matplotlib
By using style
function in Matplotlib we can apply predefined themes or create custom styles which helps in making our plots interactive. We can reuse these templates to maintain consistency across multiple plots. In this article we will see how to use Matplotlib’s built-in styles and efficiently apply them to your plots.
Syntax: plt.style.use('style_name")
- style_name is the name of the style which we want to use.
If we want to explore all the available styles we can print it like this:
from matplotlib import style
import matplotlib.pyplot as plt
print(plt.style.available)
Output:
['Solarize_Light2', '_classic_test_patch', 'bmh', ----------------seaborn-whitegrid','tableau-colorblind10']
Example 1: Applying Solarize_Light2 S
tyle
- data = np.random.randn(50): Create an array of 50 random values using numpy's randn() function which generates random values from a standard normal distribution.
- plt.style.use('Solarize_Light2'): Apply Solarize_Light2 style to the plot which helps in making the plot visually consistent with the chosen theme.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
data = np.random.randn(50)
plt.style.use('Solarize_Light2')
plt.plot(data)
plt.show()
Output:

Example 2: Applying dark_background S
tyle
- plt.style.use('dark_background'): Uses dark_background style which changes plot's background color to dark and adjusts other visual elements accordingly.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
data = np.random.randn(50)
plt.style.use('dark_background')
plt.plot(data)
plt.show()
Output:

Example 3: Applying ggplot S
tyle
- plt.style.use('ggplot'): Apply ggplot style which helps in giving it a clean and polished look similar to the popular ggplot2 library.
- plt.plot(data, linestyle=":", linewidth=2): Plot data with a dotted line style as specified by linestyle=":" and a line width of 2.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
data = np.random.randn(50)
plt.style.use('ggplot')
plt.plot(data, linestyle=":", linewidth=2)
plt.show()
Output:

Example 4: Temporarily apply dark_background S
tyle
Note: If we only want to use a style for a particular plot but don't want to change the global styling for all the plots, for that it provides a context manager for limiting the area of styling for a particular plot.
with plt.style.context('dark_background')
: Use a context manager to temporarily apply thedark_background
style to the plot within the block which ensures that only this plot is affected not others.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
with plt.style.context('dark_background'):
plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()
Output:

By using Matplotlib's styling features we can easily create visually appealing and consistent plots which helps in enhancing overall presentation of our data.