Last Updated: 

How to Change Default Background Color for Matplotlib Plots Permanently and Remove White Edges via matplotlibrc

Matplotlib is the go-to library for data visualization in Python, but its default settings—like the plain white background and thick white edges around plots—may not always align with your needs. Whether you’re creating figures for a presentation, a research paper, or a personal project, customizing these defaults can improve consistency and visual appeal.

While you can tweak plot settings temporarily using plt.rcParams or plot-specific methods, making changes permanent ensures every new plot you create adheres to your preferred style. The key to this is Matplotlib’s configuration file: matplotlibrc.

In this blog, we’ll dive deep into using matplotlibrc to:

  • Permanently set custom background colors for figures and plot areas.
  • Remove or reduce the white edges (margins) around plots.

By the end, you’ll have a personalized Matplotlib setup that saves time and elevates your visualizations.

Table of Contents#

  1. Understanding matplotlibrc
  2. Locating Your matplotlibrc File
  3. Customizing Default Background Color
    • 3.1 Figure Background (figure.facecolor)
    • 3.2 Axes Background (axes.facecolor)
  4. Removing White Edges (Margins)
    • 4.1 Adjusting Subplot Margins
    • 4.2 Avoiding Clipped Labels
  5. Applying Changes and Verification
  6. Advanced: Using a Custom matplotlibrc File
  7. Troubleshooting Common Issues
  8. Conclusion
  9. References

Understanding matplotlibrc#

matplotlibrc (pronounced “matplotlib rc”) is Matplotlib’s master configuration file. It controls nearly every default setting, from colors and fonts to line widths and tick styles. When Matplotlib initializes, it reads this file to set global parameters, making it the ideal tool for permanent customizations.

Think of matplotlibrc as a “style sheet” for your plots. Instead of adding plt.style.use('seaborn') or manually setting plt.rcParams['figure.facecolor'] = 'gray' every time, you define your preferences once in matplotlibrc, and they apply to all future plots.

Locating Your matplotlibrc File#

Before editing matplotlibrc, you need to find where it’s stored on your system. Matplotlib prioritizes configuration files in the following order (from highest to lowest priority):

  1. A custom file specified via MPLCONFIGDIR (an environment variable).
  2. A user-specific file in your home directory.
  3. A system-wide file (rarely used for personal customizations).

Step 1: Find the Active matplotlibrc Path#

Run this code to locate the matplotlibrc file Matplotlib is currently using:

import matplotlib  
print(matplotlib.matplotlib_fname())  

Example Outputs (varies by OS):

  • Linux/macOS: /home/your_username/.config/matplotlib/matplotlibrc
  • Windows: C:\Users\your_username\AppData\Roaming\matplotlib\matplotlibrc

Step 2: If No User-Specific File Exists#

If the path above points to a system directory (e.g., /usr/local/lib/python3.9/site-packages/matplotlib/mpl-data/matplotlibrc), you may not have a user-specific matplotlibrc yet. To create one:

  1. Find your Matplotlib config directory with:

    print(matplotlib.get_configdir())  

    Example: /home/your_username/.config/matplotlib (Linux/macOS) or C:\Users\your_username\AppData\Roaming\matplotlib (Windows).

  2. Navigate to this directory and create a new file named matplotlibrc (no extension).

Customizing Default Background Color#

Matplotlib has two key background layers:

  • Figure background: The outer “canvas” surrounding the plot (e.g., the area outside the axes).
  • Axes background: The inner area where data is plotted (e.g., the grid and data points).

We’ll modify both using parameters in matplotlibrc.

3.1 Figure Background: figure.facecolor#

The figure.facecolor parameter controls the color of the outer figure canvas. By default, it’s set to white (or #ffffff in hex).

How to Set It:#

Open your matplotlibrc file and search for (or add) the line:

figure.facecolor: <value>  

Replace <value> with a color specification. Valid formats include:

  • Color names: 'lightgray', 'none' (transparent), '#f0f0f0' (light gray hex).
  • Hex codes: '#1a1a1a' (dark gray), '#e6f7ff' (light blue).
  • RGB tuples: (0.9, 0.9, 0.9) (light gray, values 0–1).

Example: To set a light gray figure background:

figure.facecolor: #f0f0f0  

3.2 Axes Background: axes.facecolor#

The axes.facecolor parameter controls the color of the inner plot area (where your data lives). The default is also white.

How to Set It:#

In matplotlibrc, find or add:

axes.facecolor: <value>  

Example: To set a slightly darker gray for the plot area:

axes.facecolor: #e0e0e0  

Before-and-After Example#

To see the impact, compare a default plot with your custom settings:

Default Plot Code:

import matplotlib.pyplot as plt  
 
plt.plot([1, 2, 3], [4, 1, 3])  
plt.title("Default Background")  
plt.show()  

With Custom matplotlibrc:
After setting figure.facecolor: #f0f0f0 and axes.facecolor: #e0e0e0, the same code will produce a plot with light gray figure and axes backgrounds.

Removing White Edges (Margins)#

White edges (or margins) are the blank spaces between the figure edge and the plot area. These are controlled by subplot parameters that define the position of the axes within the figure.

4.1 Adjusting Subplot Margins#

By default, Matplotlib leaves generous margins to accommodate axis labels and titles. To reduce or remove these edges, modify the following parameters in matplotlibrc:

ParameterDefault ValueDescription
figure.subplot.left0.125Left margin (fraction of figure width)
figure.subplot.right0.9Right margin (fraction of figure width)
figure.subplot.bottom0.11Bottom margin (fraction of figure height)
figure.subplot.top0.88Top margin (fraction of figure height)

Values range from 0 (no margin) to 1 (full figure width/height).

Example: Minimizing Margins#

To reduce edges, set these parameters closer to 0 (e.g., 0.02 for tight margins):

figure.subplot.left: 0.02  
figure.subplot.right: 0.98  
figure.subplot.bottom: 0.05  
figure.subplot.top: 0.95  

4.2 Avoiding Clipped Labels#

If margins are too small, axis labels or titles may get clipped. To fix this:

  • Increase left/bottom margins slightly (e.g., 0.05 instead of 0.02).
  • Use smaller fonts (adjust axes.titlesize or axes.labelsize in matplotlibrc).
  • Add padding with axes.labelpad (e.g., axes.labelpad: 10 for 10pt padding).

Applying Changes and Verification#

After editing matplotlibrc, restart your Python kernel (or IDE) for changes to take effect. To verify:

Step 1: Check Current rcParams#

Print the updated parameters to confirm they’re loaded:

import matplotlib.pyplot as plt  
 
print("Figure facecolor:", plt.rcParams["figure.facecolor"])  
print("Axes facecolor:", plt.rcParams["axes.facecolor"])  
print("Left margin:", plt.rcParams["figure.subplot.left"])  

Step 2: Test with a Plot#

Generate a sample plot to visually confirm changes:

plt.plot([1, 2, 3], [4, 1, 3])  
plt.title("Custom Background & Reduced Margins")  
plt.xlabel("X-axis")  
plt.ylabel("Y-axis")  
plt.show()  

You should see:

  • A non-white figure background (e.g., light gray).
  • A darker gray axes background.
  • Narrower white edges around the plot.

Advanced: Using a Custom matplotlibrc File#

If you don’t want to modify the default matplotlibrc (e.g., for project-specific styles), create a custom configuration file (e.g., my_custom_rc) and load it manually.

Step 1: Create a Custom File#

Save your settings to a file (e.g., ~/custom_matplotlibrc):

# ~/custom_matplotlibrc  
figure.facecolor: #f5f5f5  
axes.facecolor: #e9e9e9  
figure.subplot.left: 0.03  
figure.subplot.right: 0.97  

Step 2: Load the Custom File#

In your Python script, load the file with:

import matplotlib.pyplot as plt  
 
plt.rc_file("~/custom_matplotlibrc")  # Path to your custom file  

This overrides the default matplotlibrc for the current session.

Troubleshooting Common Issues#

Changes Not Taking Effect?#

  • Restart your kernel/IDE: Matplotlib reads matplotlibrc only on initialization.
  • Verify the file path: Ensure you edited the matplotlibrc returned by matplotlib.matplotlib_fname().
  • Check for typos: Ensure parameter names (e.g., figure.facecolor) are spelled correctly.

Background Color Not Visible?#

  • If using figure.facecolor: none (transparent), the background may blend with your desktop/IDE theme. Test with a solid color like #f0f0f0.
  • Ensure axes.facecolor is not the same as figure.facecolor (otherwise, the axes area won’t stand out).

Labels Clipped After Reducing Margins?#

  • Increase figure.subplot.left/bottom (e.g., from 0.02 to 0.05).
  • Use plt.tight_layout() temporarily (but this overrides matplotlibrc settings for that plot).

Conclusion#

Customizing Matplotlib’s defaults via matplotlibrc is a game-changer for anyone creating frequent visualizations. By setting permanent background colors and reducing margins, you’ll save time and ensure a consistent look across all your plots.

Remember:

  • Use figure.facecolor and axes.facecolor for backgrounds.
  • Adjust figure.subplot.left/right/top/bottom to reduce margins.
  • Test changes with simple plots and verify parameters with plt.rcParams.

With these tweaks, your Matplotlib figures will look polished and professional—no extra code required!

References#