Search code examples
pythonmatplotlibseabornlegend

How to modify a legend with hatches


I have created a barplot with hatches with the code below:

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 texture
plt.legend()

plt.show()

And it outputs the following plot:

enter image description here

If I try to modify the legend to (a) add a title and (b) change the hue labels, the code breaks down, and I lose the color and hatches from the legend:

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 texture
plt.legend(title='My Title', labels=['Lunch_1','Dinner_2'], loc=1)

plt.show()

enter image description here

So my questions is: How do I add a title and modify the labels without losing the color and hatches from the legend?


Solution

  • You need to call legend with the signature legend(handles, labels) after retrieving the original ones with get_legend_handles_labels :

    handles, _ = ax.get_legend_handles_labels()
    
    plt.legend(handles, ["Lunch_1", "Dinner_2"], title="My Title", loc=1)
    

    Output :

    enter image description here