簡體   English   中英

seaborn facetgrid:當色調值未出現在所有圖表中時,圖例被錯誤注釋

[英]seaborn facetgrid: when hue value doesn't appear in all graphs the legend is misannotated

我還在 seaborn git repo 中打開了一個問題 然而,我很可能不是一個錯誤,而是我犯了一些基本錯誤 - 但我還沒有弄清楚......

問題:相同的顏色被分配給圖例中的兩個不同的值。 當我擴大到更多只包含分配給“色調”的值的子集的圖表時,如何防止這種情況發生?

要重現的代碼:

import numpy as np
import pandas as pd

import seaborn as sns
import matplotlib.pyplot as plt


sna = pd.DataFrame(
    {
        'x' : np.tile(range(10), 5), 
        'y' : list(range(10)) + list(range(2,12)) + list(range(4, 14)) + list(range(6, 16)) + list(range(8, 18)),
        'id_for_hue' : ['foo']*10 + ['bar']*10 + ['baz']*10 + ['bar']*10 + ['baz']*10,
        'id_for_graph' : ['a']*30 + ['b']*20
    }                                
)

g = sns.FacetGrid(sna, col='id_for_graph')
g.map_dataframe(
    sns.lineplot,
    x = 'x',
    y = 'y',
    hue = 'id_for_hue'
)

g.add_legend()

在此處輸入圖像描述

另一方面,如果我進行排序以使第二個圖中的值出現在數據框的頂部,那么問題就解決了。

g = sns.FacetGrid(sna.sort_values(['id_for_hue']), col='id_for_graph')
g.map_dataframe(
    sns.lineplot,
    x = 'x',
    y = 'y',
    hue = 'id_for_hue'
)

g.add_legend()

在此處輸入圖像描述

版本:

  • 海生:0.11.2
  • matplotlib:3.5.2
  • 熊貓:1.3.4
  • 麻木:1.21.6
  • 蟒蛇:3.7.6

也許不足為奇,我應該更仔細地閱讀文檔。 lineplot()文檔中所述,“使用relplot()比直接使用FacetGrid更安全,因為它確保跨方面的語義映射同步”。 事實上,在FacetGrid文檔中指出“在大多數情況下,您將希望使用圖形級別的函數(例如 displot()、relplot())來制作繪圖”。

所以,使用 relplot()。 例如

sns.relplot(
    data = sna,
    col = 'id_for_graph',
    kind = 'line',
    x = 'x',
    y = 'y',
    hue = 'id_for_hue'
)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM