首頁  >  文章  >  後端開發  >  如何控制 Seaborn 長條圖中圖例的放置?

如何控制 Seaborn 長條圖中圖例的放置?

Barbara Streisand
Barbara Streisand原創
2024-10-25 04:34:29560瀏覽

How to Control Legend Placement in Seaborn Bar Plots?

自訂Seaborn 條形圖中的圖例位置

在Seaborn 中使用Factorplot(kind="bar") 建立因子圖時,其圖例有時可能會錯位,超出情節的邊緣。這可能會使情節變得混亂且難以解釋。

為了解決此問題,seaborn 提供了多種自訂圖例放置的選項。一種方法是在 Factorplot 中使用 legend=False 並透過 matplotlib 手動處理圖例。這允許您使用 loc 參數指定圖例的位置。

以下是範例程式碼:

<code class="python">import seaborn as sns
import matplotlib.pyplot as plt

titanic = sns.load_dataset("titanic")

# Create a factor plot with legend disabled
g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)

# Customize the legend's position and appearance
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")</code>

在此範例中,despine(left=True) 函數會刪除圖例上不必要的空格。情節的左側。然後使用 legend(loc='upper left') 手動新增圖例,並將「左上角」指定為圖例的位置。您也可以使用適當的 matplotlib 函數調整圖例的標題和其他屬性。

以上是如何控制 Seaborn 長條圖中圖例的放置?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn