我使用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()
1条答案
按热度按时间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.2
、matplotlib 3.7.1
、seaborn 0.12.2
中测试