我还在seaborn git repo 中提出了一个问题here。然而,我很可能犯了一些基本错误,而不是错误 - 但我还没有弄清楚......
问题:相同的颜色被分配给图例中的两个不同的值。当我扩展到更多仅包含分配给“色调”的值的子集的图形时,如何防止这种情况发生?
要重现的代码:
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
- numpy:1.21.6
- 蟒蛇:3.7.6