简体   繁体   中英

How to get the color of a seaborn/matplotlib bar graph

I am building a seaborn graphics with this code :

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
%matplotlib inline
df=pd.DataFrame(data=['a','b','c','d','a','a','b','c','a','a'],columns['datos'])
tabla=df['datos'].value_counts().reset_index()
fig, ax1 = plt.subplots(figsize=(6,4))
sns.set()
sns.barplot(x='index', y='datos', data=tabla, ax=ax1)

It does work properly....but How could I get the code of the colors used for every bar? I have tried with :

f.get_color()
ax.get_color()

but no success at all...

thanks in advance waly

I admit it's an ugly way, but you will need to access the children of your plot. Note that this probably won't work if you plot more than just the countplot, since you will get all used Rectangle colors in your plot.

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import pandas as pd
import seaborn as sns
%matplotlib inline
sns.set()

df=pd.DataFrame(data=['a','b','c','d','a','a','b','c','a','a'],columns=['datos'])
tabla=df['datos'].value_counts().reset_index()
fig, ax1 = plt.subplots(figsize=(6,4))
sns.barplot(x='index', y='datos', data=tabla, ax=ax1)

bars = [r for r in ax1.get_children() if type(r)==Rectangle]
colors = [c.get_facecolor() for c in bars[:-1]] # I think the last Rectangle is the background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM