How to color a Seaborn boxplot based on DataFrame column name in Matplotlib?

PythonServer Side ProgrammingProgramming

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

raja
Published on 08-Jul-2021 11:20:10
Advertisements