【问题标题】:Annotate each FacetGrid subplot using custom df (or list) using a func使用 func 使用自定义 df(或列表)注释每个 FacetGrid 子图
【发布时间】:2022-08-06 01:33:12
【问题描述】:

考虑以下数据和 FacetGrid:

d = {\'SITE\':[\'A\', \'B\', \'C\', \'C\', \'A\'], \'VF\':[0.00, 0.78, 0.99, 1.00, 0.50],\'TYPE\':[\'typeA\', \'typeA\', \'typeB\', \'typeC\', \'typeD\']} 
new_df = pd.DataFrame(data=d) 


with sns.axes_style(\"white\"):
    g = sns.FacetGrid(data=new_df, col=\'SITE\', col_wrap= 3, height=7, aspect=0.25, 
                      hue=\'TYPE\', palette=[\'#1E88E5\', \'#FFC107\', \'#D81B60\'])
    g.map(sns.scatterplot, \'VF\', \'TYPE\', s=100)

使用另一个dataframe

d = {\'SITE\':[\'A\', \'B\', \'C\'], \'N\':[10, 5, 7]} 

ann_df = pd.DataFrame(data=d) 

其中SITE 与原始new_df[\'SITE\'] 匹配,new_df[\'SITE\'] 的维度不同,但在FacetGrid 中有columns 的对应长度。

你如何 annotate 每个 subplot 使用自定义 func 使用不是散点图new_df,但ann_df 或自定义list,如果它匹配原始new_df[\'SITE\'] 并将ann_df[\'N\'] 添加到每个子图,如下所示:

所以,沿着这些路线或更好的东西:

def annotate(data, **kws):
n = data           # should be the int for each matching SITE 
ax = plt.gca()
ax.text(.1, .2, f\"N = {n}\", transform=ax.transAxes)

g.map_dataframe(annotate(ann_df)) 

    标签: python-3.x pandas matplotlib seaborn plot-annotations


    【解决方案1】:
    • 建议从seaborn v0.11.0 使用像seaborn.relplot 这样的图形级函数,而不是seaborn.FacetGrid
    • col= 使用的值将默认按字母顺序绘制,否则使用col_order= 指定顺序,然后确保ann_df['SITE'] 按相同顺序排序。
    • sns.relplot 返回的seaborn.axisgrid.FacetGrid 展平,遍历matplotlib.axes,并使用i from enumerate.iloc.text 添加到每个绘图中,以索引@987654341 的正确值@。
    • answer 类似,但从辅助DataFrame 而不是dict 获取数据。
    • python 3.10pandas 1.4.2matplotlib 3.5.1seaborn 0.11.2 中测试
    import seaborn as sns
    import pandas as pd
    
    # DataFrame 1
    d1 = {'SITE':['A', 'B', 'C', 'C', 'A'],
          'VF':[0.00, 0.78, 0.99, 1.00, 0.50],
          'TYPE':['typeA', 'typeA', 'typeB', 'typeC', 'typeD']} 
    df = pd.DataFrame(data=d1)
    
    # DataFrame 2
    d2 = {'SITE':['A', 'B', 'C'], 'N':[10, 5, 7]} 
    ann_df = pd.DataFrame(data=d2) 
    
    # plot
    g = sns.relplot(kind='scatter', data=df, x='VF', y='TYPE', col='SITE',
                    col_wrap=3, height=7, aspect=0.5, hue='TYPE', s=100)
    
    # flatten axes into a 1-d array
    axes = g.axes.flatten()
    
    # iterate through the axes
    for i, ax in enumerate(axes):
        ax.text(0, 3, f"N = {ann_df.iloc[i, 1]}")
    

    【讨论】:

      猜你喜欢
      • 2022-10-12
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多