Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to color a Seaborn boxplot based on DataFrame column name in Matplotlib?
To color a Seaborn boxplot based on dataframe column name, we can take the following steps −
- Set the figure size and adjust the padding between and around the subplots.
- Make a Pandas dataframe with two columns, col1 and col2.
- Make a boxplot with horizontal orientation.
- Get the boxes artists.
- Iterate the boxes and set the facecolor of the box.
- To display the figure, use show() method.
Example
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(
[[2, 4],
[7, 2]
], columns=['col1', 'col2'])
ax = sns.boxplot(data=df, orient='h')
boxes = ax.artists
for i, box in enumerate(boxes):
if 'col1' in df.columns[i]:
box.set_facecolor('r')
else:
box.set_facecolor('b')
plt.show()
Output

Advertisements