0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Use Dark Background Style in Matplotlib

To use a dark background style in matplotlib, apply the built-in style 'dark_background' using plt.style.use('dark_background'). This changes the plot colors to suit a dark theme automatically.
๐Ÿ“

Syntax

Use plt.style.use('dark_background') before creating your plot to switch to the dark background style. This style changes the figure background to dark and adjusts colors for better visibility.

python
import matplotlib.pyplot as plt

plt.style.use('dark_background')  # Apply dark background style

plt.plot([1, 2, 3], [4, 5, 6])  # Create a simple line plot
plt.show()
Output
A plot window with a black background and bright colored lines and labels.
๐Ÿ’ป

Example

This example shows how to create a line plot with the dark background style applied. The background is black, and the lines and text use bright colors for clear visibility.

python
import matplotlib.pyplot as plt

plt.style.use('dark_background')

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]

plt.plot(x, y, marker='o', linestyle='-', color='cyan', label='Squared values')
plt.title('Dark Background Style Example')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.legend()
plt.show()
Output
A line plot with black background, cyan line with circle markers, and white axis labels and title.
โš ๏ธ

Common Pitfalls

  • Forgetting to call plt.style.use('dark_background') before plotting will keep the default light style.
  • Manually setting colors that do not contrast well with dark backgrounds can make plots hard to read.
  • Using plt.style.use after creating plots will not update existing figures.
python
import matplotlib.pyplot as plt

# Wrong: setting style after plotting
plt.plot([1, 2, 3], [4, 5, 6])
plt.style.use('dark_background')  # This won't change the existing plot
plt.show()

# Right: set style before plotting
plt.style.use('dark_background')
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Output
First plot: default white background. Second plot: black background with bright lines.
๐Ÿ“Š

Quick Reference

Use these tips to apply dark background style effectively:

  • Call plt.style.use('dark_background') before any plotting commands.
  • Choose bright colors for lines and markers to ensure visibility.
  • Combine with other style settings if needed for customization.
โœ…

Key Takeaways

Apply dark background style with plt.style.use('dark_background') before plotting.
Dark background improves visibility in low-light environments and presentations.
Use bright colors for plot elements to contrast with the dark background.
Setting style after plotting does not affect existing figures.
Combine dark background style with other customizations for best results.