Grouping columns in Seaborn barplots

Viewed 304

I have a data frame consisting of 32 columns and I wish to generate a bar plot using Seaborn with 8 different groups, each consisting of 4 columns, and with each group assigned a unique color. Each group of 4 columns represents a repeated sampling for a particular (8 different) experimental condition (they are technical replicates) and I would like to show consistency (in a purely visual manner) of sampling for each of the 8 experimental conditions.

Column structure is as follows: Index | Condition1_replicate1 | Condition1_replicate2 ... Condition8_replicate3 | Condition8_replicate4

Any help will be much appreciated!

1 Answers

You could create a color palette that repeats 8 colors 4 times:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(np.random.rand(100, 32), columns=[f'Cond{i}_r{j}' for i in range(1, 9) for j in range(1, 5)])

palette = np.repeat(sns.color_palette('Set1', 8), 4, axis=0)

fig, ax = plt.subplots(figsize=(12, 3))
sns.barplot(data=df, palette=palette, ax=ax)
ax.set_xticks([])

plt.show()

sns.barplot with repeated colors

PS: You can create a variation for the palette, e.g.

colors = sns.color_palette('Set2', 8)
palette = [color_j for color_i in colors for color_j in sns.dark_palette(color_i, 7)[-4:]]

fig, ax = plt.subplots(figsize=(12, 3))
sns.barplot(data=df, palette=palette, ax=ax)
ax.set_xticks(np.arange(1.5, 4 * 8, 4))
ax.set_xticklabels([f'Condition {i}' for i in range(1, 9)])
plt.show()

sns.barplot with different palette

Related