matplotlib 如何将影线添加到历史图条和图例

yftpprvb  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(212)

我使用seaborn创建了一个带图案填充的条形图。我还能够添加一个包含填充样式的图例,如下面的MWE所示:

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()

然而,当我尝试在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()

dldeef67

dldeef671#

问题是ax1.get_legend_handles_labels()返回seaborn.histplot的空列表。请参阅此answer。通过将ax=ax添加到seaborn.histplot(...)来使用显式接口。使用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()

相关问题