How can I change the opacity of my each bar in barplot by their values seaborn?

Viewed 3684

I have a dataframe like this in which I created barplot by seaborn

sns.barplot(x='year', y='counts', data=df, color='red', alpha=df_alpha.alpha)
df.head()
    year    counts   alpha
0   2014    16908   1.000000
1   2015    14977   0.894269
2   2016    13626   0.820296
3   2013    12041   0.733510
4   2017    10980   0.675415

How can I set df's alpha values as corresponding alpha's values? I created alpha values column by MinMaxScaler and scaled the counts between (0.1,1) Therefore least count bar would have 0.1 opacity and viceversa.

1 Answers

To change the alpha of the bars, you need to explicitly loop through the generated bars and change their alpha. To make sure that the bars occur in the same order as in the dataframe, the order= parameter should be set.

In the example below, darkred is used for the bars, to better see the differences in alpha.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from io import StringIO

df_str = '''    year    counts   alpha
0   2014    16908   1.000000
1   2015    14977   0.894269
2   2016    13626   0.820296
3   2013    12041   0.733510
4   2017    10980   0.675415'''

df = pd.read_csv(StringIO(df_str), delim_whitespace=True)
ax = sns.barplot(x='year', y='counts', data=df, color='darkred', order=df['year'])
for bar, alpha in zip(ax.containers[0], df['alpha']):
    bar.set_alpha(alpha)
plt.show()

resulting plot

Related