How to change the color of a single bar if a condition is true (Matplotlib)?

To change the color of a single bar based on a condition in Matplotlib, we can create a list of colors that applies different colors based on our criteria. This technique is useful for highlighting specific data points in bar charts.

Steps

  • Set the figure size and adjust the padding between and around the subplots.
  • Initialize a variable for bar width.
  • Create lists of values and corresponding colors based on conditions.
  • Use bar() method to plot bars with conditional colors.
  • To display the figure, use show() method.

Example

Here's how to highlight bars with value 2 in yellow while keeping others red ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.arange(5)
width = 0.5
vals = [1, 2, 1, 5, 3]
colors = ["red" if i != 2 else "yellow" for i in vals]

plt.bar(data, vals, width, color=colors)
plt.title("Bar Chart with Conditional Coloring")
plt.xlabel("Index")
plt.ylabel("Values")
plt.show()

Multiple Conditions Example

You can also apply multiple conditions for different color schemes ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [8.00, 4.00]
plt.rcParams["figure.autolayout"] = True

data = np.arange(6)
vals = [1, 4, 2, 7, 3, 5]

# Multiple conditions: green for >5, yellow for ==2, red for others
colors = []
for val in vals:
    if val > 5:
        colors.append("green")
    elif val == 2:
        colors.append("yellow")
    else:
        colors.append("red")

plt.bar(data, vals, width=0.6, color=colors)
plt.title("Bar Chart with Multiple Color Conditions")
plt.xlabel("Index")
plt.ylabel("Values")
plt.show()

Using Color Maps

For more sophisticated coloring, you can use matplotlib's color maps ?

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(5)
vals = [1, 8, 3, 6, 4]
threshold = 5

# Use colormap based on threshold
colors = plt.cm.RdYlGn([1 if val > threshold else 0 for val in vals])

plt.bar(data, vals, color=colors)
plt.title("Bar Chart with Colormap-based Conditional Coloring")
plt.xlabel("Index")
plt.ylabel("Values")
plt.axhline(y=threshold, color='black', linestyle='--', alpha=0.7, label=f'Threshold ({threshold})')
plt.legend()
plt.show()

Conclusion

Conditional bar coloring in Matplotlib is achieved by creating a list of colors based on your data conditions. Use list comprehensions for simple conditions or loops for complex multi−condition scenarios.

Updated on: 2026-03-25T21:31:59+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements