lucatrovato
lucatrovato

Reputation: 3

Create a "stacked" bar chart according to one boolean column

I would like to create a single bar which is composed of multiple layers stacked on top of each other, where each layer is colored according to a boolean flag (contained for example in a dataframe).

The final effect should be something like the picture below, but I would be using a large set (40'000 entries).

Anybody knows if this can be easily done with seaborn or matplotlib?

Thanks a lot!

Picture

Upvotes: 0

Views: 168

Answers (1)

JohanC
JohanC

Reputation: 80409

You could convert the dataframe column to a 2D numpy array and use sns.heatmap():

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

df = pd.DataFrame({'bool_val': np.random.randn(40000).cumsum() > 0})
ax = sns.heatmap(data=df['bool_val'].to_numpy().reshape(-1, 1),
                 cmap=sns.color_palette(['crimson', 'gold'], as_cmap=True), square=False, cbar=False)
ax.set_xticks([])
yticks = np.arange(0, len(df), 5000)
ax.set_yticks(yticks)
ax.set_yticklabels(yticks)
plt.show()

heatmap from one column

Upvotes: 1

Related Questions