Change Background Color of Matplotlib Subplot Based on Value

Recently, while working on a Python data visualization project, I wanted to highlight how different metrics performed across multiple plots. Each subplot represented a different region in the United States, and I wanted the background color of each subplot to reflect its performance level, green for good, yellow for average, and red for poor.

In this tutorial, I’ll show you how to change background color of subplots according to values in Python using Matplotlib. We’ll explore multiple methods, including an easy conditional approach and a more dynamic method using loops and color mapping.

By the end of this guide, you’ll be able to make your Python data visualizations more insightful and visually appealing, just like a professional dashboard.

Method 1 – Change Subplot Background Color Using Conditional Logic

This is the simplest way to color your subplots based on data values. We’ll use basic conditional statements in Python to apply different colors depending on the value of each dataset.

Step 1: Import Required Python Libraries

We’ll start by importing Matplotlib and NumPy. NumPy will help us generate random data to simulate real-world scenarios.

import matplotlib.pyplot as plt
import numpy as np

Step 2: Create Sample Data

For this example, let’s assume we’re analyzing average monthly sales (in thousands of dollars) for four different U.S. regions. We’ll create random values for simplicity.

# Sample sales data (in thousands)
regions = ['East', 'West', 'North', 'South']
sales = [85, 60, 45, 95]  # Example data values

Step 3: Create Subplots in Python

We’ll create a 2×2 grid of subplots using Matplotlib’s plt.subplots() method. Each subplot will represent one region.

fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes = axes.flatten()  # Flatten for easy iteration

Step 4: Apply Conditional Background Colors

Now comes the interesting part. We’ll assign background colors based on the sales performance for each region.

for i, ax in enumerate(axes):
    value = sales[i]
    region = regions[i]

    # Conditional background color logic
    if value >= 80:
        color = 'lightgreen'
    elif 50 <= value < 80:
        color = 'khaki'
    else:
        color = 'lightcoral'

    # Set subplot face color
    ax.set_facecolor(color)

    # Plot the bar
    ax.bar(region, value, color='steelblue')
    ax.set_title(f"{region} Region\nSales: ${value}K", fontsize=12)
    ax.set_ylim(0, 100)

Step 5: Final Touches

Let’s add a main title and adjust spacing for a cleaner layout.

fig.suptitle("Regional Sales Performance (Background Color by Value)", fontsize=14, weight='bold')
plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()

Output

You’ll see four subplots:

  • The East and South regions will have a green background (high sales).
  • The West region will appear yellow (moderate sales).
  • The North region will show a red background (low sales).

I have executed the above example code and added the screenshot below.

Change Background Color of Subplots According to Values

This helps you instantly identify performance levels without reading the numbers.

Method 2 – Change Subplot Background Using a Color Map

While the first method works great for fixed thresholds, sometimes you want a more dynamic or gradient-based approach. In this method, we’ll use Matplotlib’s color maps to automatically assign colors based on numeric values.

Step 1: Import Required Python Modules

We’ll use the same imports as before, but this time we’ll also use Matplotlib’s cm (color map) module.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

Step 2: Generate Example Data

Let’s simulate average customer satisfaction scores (out of 100) for four U.S. cities.

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston']
scores = [92, 78, 55, 30]

Step 3: Normalize Data for Color Mapping

We’ll normalize the scores so that they fit within the 0–1 range required by the color map.

norm = plt.Normalize(min(scores), max(scores))
colors = cm.RdYlGn(norm(scores))  # Red-Yellow-Green color map

Step 4: Create Subplots and Apply Color Map

Now we’ll create subplots and assign each subplot’s background color based on its score.

fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes = axes.flatten()

for i, ax in enumerate(axes):
    ax.set_facecolor(colors[i])
    ax.bar(cities[i], scores[i], color='gray')
    ax.set_title(f"{cities[i]}\nScore: {scores[i]}", fontsize=12)
    ax.set_ylim(0, 100)

Step 5: Add a Color Bar and Display

To make the visualization even more informative, let’s add a color bar that shows the mapping between colors and values.

sm = plt.cm.ScalarMappable(cmap=cm.RdYlGn, norm=norm)
sm.set_array([])

fig.colorbar(sm, ax=axes, orientation='horizontal', fraction=0.05, pad=0.1, label='Satisfaction Score')
fig.suptitle("Customer Satisfaction by City (Color Mapped Backgrounds)", fontsize=14, weight='bold')
plt.tight_layout(rect=[0, 0, 1, 0.92])
plt.show()

Output

You’ll see:

  • Green backgrounds for cities with high satisfaction scores.
  • Yellow for mid-range scores.
  • Red for low scores.

I have executed the above example code and added the screenshot below.

Change Background Color of Subplot According to Value

This method gives your Python visualization a professional, dashboard-like appearance.

Method 3 – Use Conditional Color Mapping with Pandas (Optional)

If you’re working with large datasets, using Pandas can make the process smoother. Let’s quickly look at how we can integrate this logic with Pandas DataFrames.

Step 1: Import Libraries and Create a DataFrame

Import pandas and matplotlib, then build a DataFrame of states and their growth rates.

import pandas as pd
import matplotlib.pyplot as plt

data = {
    'State': ['California', 'Texas', 'Florida', 'New York'],
    'GrowthRate': [4.5, 2.8, 3.9, 1.5]
}

df = pd.DataFrame(data)

Step 2: Create Subplots and Color Logic

Create 2×2 subplots, decide background color per rate, set `ax.set_facecolor()` and draw the bar.

fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes = axes.flatten()

for i, ax in enumerate(axes):
    state = df.loc[i, 'State']
    rate = df.loc[i, 'GrowthRate']

    if rate > 4:
        color = 'lightgreen'
    elif rate > 2:
        color = 'khaki'
    else:
        color = 'lightcoral'

    ax.set_facecolor(color)
    ax.bar(state, rate, color='navy')
    ax.set_title(f"{state}\nGrowth Rate: {rate}%", fontsize=12)
    ax.set_ylim(0, 6)

Step 3: Display the Chart

Add a suptitle, tighten layout, and call `plt.show()` to display the chart.

plt.suptitle("State Growth Rates (Colored by Performance)", fontsize=14, weight='bold')
plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()

I have executed the above example code and added the screenshot below.

Change Background Color of Matplotlib Subplots According to Values

This approach works beautifully when you’re analyzing state-wise or region-wise performance data in Python. It’s also scalable; you can easily extend it to dozens of subplots dynamically.

Pro Tips

  • Use consistent color schemes across charts for better readability.
  • When using color maps, choose one that aligns with your data’s meaning (e.g., red-to-green for performance).
  • Avoid overly bright backgrounds; keep it subtle for better contrast with plotted data.
  • For dashboards, you can integrate this logic with Plotly or Dash for interactive visuals.

Changing the background color of subplots according to values in Python is a simple yet powerful way to make your visualizations more meaningful. Whether you’re analyzing sales, performance, or satisfaction scores, color-coded backgrounds instantly communicate insights without requiring extra labels or legends.

In this tutorial, I shared multiple ways to achieve this, from basic conditional logic to advanced color mapping with Matplotlib and Pandas. You can easily adapt these methods to your own datasets and use them in professional dashboards or reports.

You may also like to read the other articles:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.