How do I make bar plots automatically cycle across different colors?

To make bar plots automatically cycle across different colors, we can use matplotlib's cycler to set up automatic color rotation for each bar group. This ensures each data series gets a distinct color without manual specification.

Steps to Create Color-Cycling Bar Plots

  • Set the figure size and adjust the padding between and around the subplots
  • Configure automatic cycler for different colors using plt.cycler()
  • Create a Pandas DataFrame with the data to plot
  • Use plot() method with kind="bar" to create the bar chart
  • Display the figure using show() method

Example

Here's how to create a bar plot with automatic color cycling ?

import matplotlib.pyplot as plt
import pandas as pd

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

# Set automatic color cycler
plt.rc('axes', prop_cycle=(plt.cycler('color', ['r', 'g', 'b', 'y'])))

# Create DataFrame
df = pd.DataFrame({
    'name': ["John", "Jacks", "James"], 
    'age': [23, 20, 26],
    'marks': [88, 90, 76], 
    'salary': [90, 89, 98]
})

# Create bar plot with automatic color cycling
df.set_index('name').plot(kind='bar')

plt.show()

The output shows a bar chart where each data series (age, marks, salary) automatically gets a different color from the cycler ?

Bar chart with three groups of bars, each series colored differently:
- Age bars: red
- Marks bars: green  
- Salary bars: blue

Customizing Color Cycles

You can customize the color cycle with different colors or color schemes ?

import matplotlib.pyplot as plt
import pandas as pd

# Custom color palette
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
plt.rc('axes', prop_cycle=(plt.cycler('color', colors)))

# Sample data
data = pd.DataFrame({
    'Product': ['A', 'B', 'C', 'D'],
    'Q1': [20, 35, 30, 25],
    'Q2': [25, 30, 35, 30],
    'Q3': [30, 25, 40, 35],
    'Q4': [35, 40, 25, 40]
})

data.set_index('Product').plot(kind='bar', figsize=(8, 4))
plt.title('Quarterly Sales Data')
plt.ylabel('Sales')
plt.show()

This creates a bar chart with custom hex colors that cycle through the specified palette.

Key Points

  • prop_cycle: Controls the automatic cycling of plot properties like colors
  • plt.cycler(): Creates a cycler object that rotates through specified values
  • Colors cycle automatically: Each new data series gets the next color in the cycle
  • Resets after cycle completes: Colors repeat if you have more series than colors

Conclusion

Using plt.rc() with prop_cycle and plt.cycler() automatically assigns different colors to each data series in bar plots. This eliminates the need to manually specify colors and ensures consistent, visually distinct bars across your data.

Updated on: 2026-03-25T21:37:34+05:30

891 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements