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

Barbara Streisand
發布: 2024-10-25 04:34:29
原創
570 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!