Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to color a Seaborn boxplot based on DataFrame column name in Matplotlib?
To color a Seaborn boxplot based on DataFrame column names, you need to access the box artists and set their facecolor based on specific column conditions. This approach gives you fine−grained control over individual box colors.
Basic Setup
First, let's create a sample DataFrame and generate a basic boxplot ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create sample data
df = pd.DataFrame({
'col1': [2, 4, 6, 8, 10, 3, 5],
'col2': [7, 2, 9, 1, 4, 8, 6]
})
print("DataFrame:")
print(df.head())
DataFrame: col1 col2 0 2 7 1 4 2 2 6 9 3 8 1 4 10 4
Coloring Boxes by Column Name
Access the box artists and apply colors based on column names ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [8.00, 4.00]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({
'col1': [2, 4, 6, 8, 10, 3, 5],
'col2': [7, 2, 9, 1, 4, 8, 6]
})
# Create horizontal boxplot
ax = sns.boxplot(data=df, orient='h')
# Get box artists
boxes = ax.artists
# Color boxes based on column names
for i, box in enumerate(boxes):
if 'col1' in df.columns[i]:
box.set_facecolor('red')
else:
box.set_facecolor('blue')
plt.title('Boxplot Colored by Column Name')
plt.show()
Advanced Coloring with Custom Logic
You can implement more sophisticated coloring logic based on column properties ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Create DataFrame with descriptive column names
df = pd.DataFrame({
'sales': [100, 150, 200, 180, 120, 90, 160],
'profit': [20, 30, 45, 35, 25, 15, 32],
'cost': [80, 120, 155, 145, 95, 75, 128]
})
fig, ax = plt.subplots(figsize=(10, 5))
# Create boxplot
boxplot = sns.boxplot(data=df, orient='h', ax=ax)
# Define color mapping
color_map = {
'sales': 'lightgreen',
'profit': 'gold',
'cost': 'lightcoral'
}
# Apply colors
boxes = ax.artists
for i, box in enumerate(boxes):
column_name = df.columns[i]
box.set_facecolor(color_map.get(column_name, 'gray'))
box.set_alpha(0.7)
plt.title('Business Metrics Boxplot with Custom Colors')
plt.xlabel('Values')
plt.show()
Key Points
- ax.artists − Returns list of box patch objects
- set_facecolor() − Changes the fill color of boxes
- enumerate() − Provides index to match boxes with column names
- orient='h' − Creates horizontal boxplots for better readability
Alternative Approach Using Hue
For categorical data, you can use the hue parameter for automatic coloring ?
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# Melt DataFrame for hue-based coloring
df = pd.DataFrame({
'group_A': [10, 15, 12, 18, 14],
'group_B': [20, 25, 22, 28, 24]
})
df_melted = df.melt(var_name='group', value_name='value')
print("Melted DataFrame:")
print(df_melted.head())
# Create boxplot with hue
plt.figure(figsize=(8, 5))
sns.boxplot(data=df_melted, x='group', y='value', hue='group')
plt.title('Boxplot Using Hue Parameter')
plt.show()
Melted DataFrame:
group value
0 group_A 10
1 group_A 15
2 group_A 12
3 group_A 18
4 group_A 14
Conclusion
Use ax.artists to access individual boxes and set_facecolor() for custom coloring based on column names. For automatic coloring, consider using the hue parameter with melted data.
Advertisements
