代码之家  ›  专栏  ›  技术社区  ›  santoku

Seaborn Relplot:如何控制图例的位置并添加标题

  •  3
  • santoku  · 技术社区  · 6 年前

    对于python relplot,如何控制图例的位置并添加绘图标题?我试过 plt.title('title') 但它不起作用。

    import seaborn as sns
    
    dots = sns.load_dataset("dots")
    
    # Plot the lines on two facets
    sns.relplot(x="time", y="firing_rate",
                hue="coherence", size="choice", col="align",
                size_order=["T1", "T2"], 
                height=5, aspect=.75, facet_kws=dict(sharex=False),
                kind="line", legend="full", data=dots)
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   DavidG    6 年前

    更改matplotlib中图例位置的一种典型方法是使用参数 loc bbox_to_anchor .
    在西伯利亚 relplot 将返回FacetGrid对象。为了获得图例对象,我们可以使用 _legend . 然后我们可以设置 洛克 BBOXY-TA锚 :

    g = sns.relplot(...)
    
    leg = g._legend
    leg.set_bbox_to_anchor([0.5, 0.5])  # coordinates of lower left of bounding box
    leg._loc = 2  # if required you can set the loc
    

    理解 BBOXY-TA锚 看见 What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?

    这同样适用于标题。matplotlib参数是 suptitle . 但我们需要图形对象。所以我们可以使用

    g.fig.suptitle("My Title")
    

    把这些放在一起:

    import seaborn as sns
    
    dots = sns.load_dataset("dots")
    
    # Plot the lines on two facets
    g = sns.relplot(x="time", y="firing_rate",
                hue="coherence", size="choice", col="align",
                size_order=["T1", "T2"],
                height=5, aspect=.75, facet_kws=dict(sharex=False),
                kind="line", legend="full", data=dots)
    
    g.fig.suptitle("My Title")
    
    leg = g._legend
    leg.set_bbox_to_anchor([1,0.7])  # change the values here to move the legend box
    # I am not using loc in this example
    

    enter image description here

    更新
    您可以通过提供X和Y坐标(图形坐标)来更改标题的位置,这样子标题就不会重叠。

    g.fig.suptitle("My Title", x=0.4, y=0.98)
    

    尽管我可能会稍微向下移动您的子图,并将图形标题保留在它使用的位置:

    plt.subplots_adjust(top=0.85)