Explain Codes LogoExplain Codes Logo

How to change plot background color?

python
matplotlib
plotting
customization
Alex KataevbyAlex Kataev·Jan 1, 2025
TLDR

Set the plot background color in Matplotlib by altering the facecolor attribute as shown:

import matplotlib.pyplot as plt # Change axes background color ax = plt.gca() ax.set_facecolor('cyan') # Plotting area is looking pretty cyan-tastic, right? # Change figure background color plt.gcf().set_facecolor('yellow') # The surrounding figure area is getting a sunny makeover here! plt.show()

To customize the plot's (axes) appearance, use ax.set_facecolor(). And for the surrounding figure area, plt.gcf().set_facecolor() serves the purpose.

Color it your way – Customize backgrounds

Targeted color changes with OO interface

Use the object-oriented interface (OOI) in Matplotlib for precise tweaks like changing background colors:

fig, ax = plt.subplots() ax.set_facecolor('#FFDD44') # Hex color, because hex is cool. # or ax.set_facecolor((1.0, 0.5, 0.2)) # RGB, because why not? Creativity has no limit! plt.show()

Consistency across plots with rcParams

Want the same look for all your plots? rcParams to the rescue! Set the color once, and forget about it:

import matplotlib as mpl mpl.rcParams.update({ 'axes.facecolor': 'beige', # All plot backgrounds are rocking beige now! 'figure.facecolor': 'ivory' # The surrounding figure just turned classically ivory! })

Note: axisbg is outdated, use ax.set_facecolor or ax.patch.set_facecolor instead.

Picking the right color

Fancy color names and palettes

Matplotlib takes color selection to the next level: named colors, Tableau 'T10' categorical palette, and colors from the unique xkcd color survey.

# Named color ax.set_facecolor('chartreuse') # XKCD color ax.set_facecolor('xkcd:mango') # Mango color from xkcd survey, because who doesn't love mangoes?

Going grayscale

Keep it professional and minimalistic with grayscale:

ax.set_facecolor('0.75') # Dark gray, where 0 (black) and 1 (white) define the extremes of your grayscale life.

Transparency and Hex in action

Experience the power of RGBA values and Hex codes:

ax.set_facecolor((0, 0, 1, 0.1)) # Blue with 10% opacity, because subtlety never goes out of style! ax.set_facecolor('#004488') # Hex color code, because every cool artist has a secret code!

Troubleshooting

No color changes in the plot? Make sure they happen before the plt.show() call!