如何获取 seaborn/matplotlib 条形图的颜色

3

我正在使用以下代码构建一个seaborn图形:

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)

它确实可以正常工作...但是我该如何获取每个条形图使用的颜色代码? 我已经尝试过使用:

f.get_color()
ax.get_color()

但是完全没有成功...
提前感谢 waly
1个回答

4

我承认这是一种不太美观的方式,但是您需要访问绘图的子元素。请注意,如果您绘制的不仅仅是计数图,则可能无法正常工作,因为您将获取绘图中使用的所有矩形颜色。

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.

谢谢pask!..它有效!...我想要添加一个只包含'c'和'd'计数的额外图形,但使用与之前相同的颜色..所以我需要获取两者:'colors[2:]'....谢谢! - mharias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接