【问题标题】:How to change z-order of plotting in seaborn pairplot如何更改 seaborn pairplot 中的绘图顺序?
【发布时间】:2023-03-08 04:24:02
【问题描述】:

以下代码生成一个 seaborn 配对图。

我怎样才能使红点(b = 10.)在子图 c/a(左下角)中可见?

目前它几乎不可见,因为带有b = 4b = 5 的点似乎在之后被绘制并隐藏了。

不幸的是,对 DataFrame 进行排序没有帮助。

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

def supplyHueByB(x, bMax):
    amountOfSegments = 8
    myReturn = int(x * amountOfSegments / bMax)
    return myReturn

myList = [
    [0.854297, 1.973376, 0.187038],
    [0.854297, 2.204028, 0.012476],
    [0.854297, 10.0, 0.056573],
    [0.854297, 5.0, 0.050635],
    [0.854297, 4.0, 0.058926]
]
df = pd.DataFrame(myList)
df.columns=['a', 'b', 'c']
bMax = df.b.max()
hue = df.b.apply(lambda x: supplyHueByB(x, bMax))

g = sns.pairplot(
    df,
    corner=True,
    diag_kws=dict(color=".6"),
    vars=['a', 'b', 'c'],
    plot_kws=dict(
        hue=hue,
        palette="coolwarm",
        edgecolor='None',
        s=80  # size
    ),
)

plt.subplots_adjust(bottom=0.1)
g.add_legend()
plt.show()

【问题讨论】:

    标签: python seaborn


    【解决方案1】:

    dfhue 必须串联排序:

    >>> g = sns.pairplot(
    ...     df.sort_values('b'),
    ...     corner=True,
    ...     diag_kws=dict(color=".6"),
    ...     vars=['a', 'b', 'c'],
    ...     plot_kws=dict(
    ...         hue=sorted(hue),
    ...         palette="coolwarm",
    ...         edgecolor='None',
    ...         s=80  # size
    ...     ),
    ... )
    

    上面产生了所需的输出,即红点绘制在浅蓝色点之后。在这个例子中,使用sort_valuessorted 就可以了。对于绘制点的自定义顺序,可能需要更有创意,但关键原则仍然是df 的顺序应与hue 的顺序一致。

    【讨论】:

    • 不错。我没有意识到 OP 希望将点按hue 的顺序放置在图表上。
    【解决方案2】:

    我很惊讶地看到 Seaborn 并没有按照点通过的顺序执行分层(即哪个点高于另一个点),因为 Matplotlib 肯定会这样做,而且 Seaborn 是在 Matplotlib 之上构建的。

    按照 Matplotlib 的顺序,您希望点 [a=0.854297, c=0.056573](即被隐藏的点)绘制在靠近它的其他两个点 [a=0.854297, c=0.050635][a=0.854297, c=0.058926] 之后。这样[a=0.854297, c=0.056573] 会被绘制在最后,因此不会被屏蔽。

    由于 Seaborn 似乎没有开箱即用地执行此操作,因此我将 [a=0.854297, c=0.056573] 重新排序为最后绘制。

    # layer_orders is the order (first to last) in which we want the points to be plotted.
    layer_order = [0, 1, 3, 4, 2]
    
    # Extracting df['a'] and df['c'] in the order we want.
    a = df['a'][layer_order]
    c = df['c'][layer_order]
    
    # Highlighting the last point in red to show it is not hidden.
    colors = ['blue'] * 4 + ['red']
    
    # Axis 3 is where we have the problem. Clearing its contents first.
    g.figure.axes[3].clear()
    g.figure.axes[3].scatter(a, c, color=colors)
    

    这将为您提供如下所示的情节:

    您可能希望将代码重构得更好,但我希望这可以为您提供基本思路。

    [我已经用蓝色和红色绘制了点,但是您可以将它们更改为您喜欢的十六进制值以匹配其他 Seaborn 图。]

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多