Seaborn:如何更改直方图中各个条形的颜色?

Seaborn: How to change the color of individual bars in histogram?

我在互联网上查找,但没有得到任何解决方案。

我有这张图,我想更改第一个条形的颜色,如果我使用参数 'color' 它会更改所有条形。

这可以吗? 非常感谢!

嗯,确切的方法取决于您使用的地图软件。最好的办法是将数据分成两组,一组用于第一个柱,一组用于其余柱。您应该能够以自己的颜色输出每个集合。

使用:

import seaborn as sns
s = [1,1,2,2,1,3,4]
s = pd.DataFrame({'val': s, 'col':['1' if x==1 else '0' for x in s]})
sns.histplot(data=s, x="val", hue="col")

输出:

您可以通过 ax.patches 访问生成的矩形列表,然后为第一个矩形重新着色:

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

df = pd.DataFrame({'Sales': 100000 * (np.random.rand(80) ** 1.5) + 18000})
ax = sns.histplot(x='Sales', data=df, bins=4, color='skyblue', alpha=1)
ax.patches[0].set_facecolor('salmon')
plt.show()

要准确分离 40.000,您可以在同一个子图上创建两个直方图。使用 binrange= 可以设置确切的限制:

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

df = pd.DataFrame({'Sales': 100000 * (np.random.rand(80) ** 1.5) + 18000})
# either choose a fixed limit, or set it exactly at one fourth
limit = 40000
# limit = df['Sales'].min() + 0.25 * (df['Sales'].max() - df['Sales'].min())
ax = sns.histplot(x='Sales', data=df[df['Sales'] <= limit],
                  bins=1, binrange=(df['Sales'].min(), limit), color='salmon')
sns.histplot(x='Sales', data=df[df['Sales'] > limit],
             bins=3, binrange=(limit, df['Sales'].max()), color='skyblue', ax=ax)
plt.show()