首頁  >  文章  >  後端開發  >  如何自訂 Seaborn 長條圖中圖例的位置?

如何自訂 Seaborn 長條圖中圖例的位置?

Patricia Arquette
Patricia Arquette原創
2024-10-25 09:40:03606瀏覽

How to Customize the Placement of the Legend in Seaborn Bar Plots?

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

使用seaborn的factorplot(kind="bar")時,常會遇到圖例定位問題,尤其是當圖例阻礙繪圖或超出陰影區域時。本文介紹如何將圖例重新定位到更適合的位置,例如左上角。

解:

要移動圖例,請使用圖例=因子圖中的錯誤參數。這會停用預設圖例位置並允許透過 Matplotlib 進行手動控制。以下程式碼示範如何將圖例放置在左上角:

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

sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")</code>

其他注意事項:

  • 要從FacetGrid 存取軸,使用g.fig .get_axes()[0]:
<code class="python">g.fig.get_axes()[0].legend(loc='lower left')</code>

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

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