如何在histplot柱状图和图例中添加填充。

3

我使用 seaborn 创建了一个带有阴影的条形图。我还能够添加一个包含阴影样式的图例,如下所示:

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

hatches = ['\\\\', '//']

fig, ax = plt.subplots(figsize=(6,3))
sns.barplot(data=tips, x="day", y="total_bill", hue="time")

# loop through days
for hues, hatch in zip(ax.containers, hatches):
    # set a different hatch for each time
    for hue in hues:
        hue.set_hatch(hatch)

# add legend with hatches
plt.legend().loc='best'

plt.show()

enter image description here

然而,当我尝试在具有图例的seaborn上创建直方图时,相同的代码不起作用;我收到以下错误:No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument. 我已经在网上寻找答案,但没有成功找到。
如何将阴影添加到下面的MWE直方图的图例中?
import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

hatches = ['\\\\', '//']

fig, ax = plt.subplots(figsize=(6,3))
sns.histplot(data=tips, x="total_bill", hue="time", multiple='stack')

# loop through days
for hues, hatch in zip(ax.containers, hatches):
    # set a different hatch for each time
    for hue in hues:
        hue.set_hatch(hatch)

# add legend with hatches
plt.legend().loc='best' # this does not work

plt.show()

enter image description here

1个回答

3
问题是ax1.get_legend_handles_labels()对于seaborn.histplot返回空列表。请参考答案。通过在seaborn.histplot(...)中添加ax=ax使用显式接口。使用ax.get_legend().legend_handles(.legendHandles已弃用)获取图例的句柄,并使用set_hatch()添加阴影。

ax.get_legend().legend_handles返回的句柄与container相比顺序相反,因此可以使用[::-1]来反转顺序。

python 3.11.2matplotlib 3.7.1seaborn 0.12.2 中进行了测试

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

hatches = ['\\\\', '//']

fig, ax = plt.subplots(figsize=(6, 3))
sns.histplot(data=tips, x="total_bill", hue="time", multiple='stack', ax=ax)  # added ax=ax

# iterate through each container, hatch, and legend handle
for container, hatch, handle in zip(ax.containers, hatches, ax.get_legend().legend_handles[::-1]):
    
    # update the hatching in the legend handle
    handle.set_hatch(hatch)
    
    # iterate through each rectangle in the container
    for rectangle in container:

        # set the rectangle hatch
        rectangle.set_hatch(hatch)

plt.show()

enter image description here


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