pythonpandasmatplotlib

sns.histplot does not fully show the legend when setting the legend outside the axes


I tried to create a histogram with a legend outside the axes. Here is my code:

import pandas as pd
import seaborn as sns

df_long = pd.DataFrame({
    "Category": ["A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"],
    "Round": ["Round1", "Round1", "Round1", "Round1", "Round2", "Round2", "Round2", "Round2", "Round3", "Round3", "Round3", "Round3", "Round4", "Round4", "Round4", "Round4"],
    "Value": [10, 20, 10, 30, 20, 25, 15, 25, 12, 15, 19, 6, 10, 29, 13, 19]
  })
ax = sns.histplot(df_long, x="Category", hue="Round", weights="Value",
                  multiple="stack",
                  shrink=.8,
                  )
ax.set_ylabel('Weight')
legend = ax.get_legend()
legend.set_bbox_to_anchor((1, 1))

It works fine in jupyter notebook:

enter image description here

But, if I try to create a png or pdf using matplotlib, the legend is not displayed completely.

import matplotlib.pyplot as plt

plt.savefig("histogram.png")
plt.savefig("histogram.pdf")

enter image description here

I've already tried to adjust the size of the graph by using plt.figure(figsize=(4, 4)) and the problem still exist.


Solution

  • The solution is to use bbox_inches = 'tight' in the plt.savefig() function:

    import matplotlib.pyplot as plt
    
    plt.savefig("histogram.png",bbox_inches='tight')
    plt.savefig("histogram.pdf", bbox_inches='tight')
    

    enter image description here