【问题标题】:How to annotate marginal plots / distribution plots in seaborn jointgrid / jointplot如何在 seaborn 联合网格/联合图中注释边缘图/分布图
【发布时间】:2019-04-30 09:59:58
【问题描述】:

我没有在这个方向找到任何东西,但如果我错了,请告诉我。

对于来自 seaborn 的jointgrid 方法和jointplot 方法都提出了这个问题,因为到目前为止它们都为我提供了相同的基本结果。但是,如果一种方法对以下问题更好,那没问题。到目前为止,这是我的联合图示例:

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

df=pd.DataFrame(np.random.rand(100,2),columns=['x','y'])

fig=sns.jointplot(x=df['x'],y=df['y'])
fig=fig.plot_joint(plt.scatter)
fig=fig.plot_marginals(sns.distplot,kde=False)

导致

现在我想用文字评论 x 和 y 轴上的分布图形。最后,在每个条形端上方应该有这个箱的总分布的百分比。但我不知道如何连接它。

使用普通的 distplot 我的代码看起来像这样。

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

df=pd.DataFrame(np.random.rand(100,2),columns=['x','y'])

total = float(len(df['x']))
ax=sns.distplot(df['x'],kde=False)
for p in ax.patches:
    height = p.get_height()
    print(p)
    ax.text(p.get_x()+p.get_width()/2.,
            height,
            '{:1.0f}'.format((height/total)*100),
            ha="center")

但是如何在jointplot的分布图上获得注释呢?

【问题讨论】:

    标签: python matplotlib plot annotations seaborn


    【解决方案1】:

    我不知道你为什么要策划两次。您只需要绘制一次,然后提取补丁并使用文本以正确的坐标进行注释

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    df=pd.DataFrame(np.random.rand(100,2),columns=['x','y'])
    total = float(len(df['x']))
    
    fig=sns.jointplot(x=df['x'],y=df['y'])
    
    for p in fig.ax_marg_x.patches:
        height = p.get_height()
        fig.ax_marg_x.text(p.get_x()+p.get_width()/2.,height,
                '{:1.0f}'.format((height/total)*100), ha="center")
    
    for p in fig.ax_marg_y.patches:
        width = p.get_width()
        fig.ax_marg_y.text(p.get_x()+p.get_width(),p.get_y()+p.get_height()/2., 
                '{:1.0f}'.format((width/total)*100), va="center")    
    

    【讨论】:

    • 非常感谢。你对jointplot是对的,没有必要再次填充情节。就用jointgrid。我只是不知道如何处理边距图 - 现在使用:“ fig.ax_marg_x.patches ”。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2022-08-18
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多