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

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    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:

    [​IMG]

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


    [​IMG]

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

    Continue reading...

Compartilhe esta Página