簡體   English   中英

如何將數據標簽添加到seaborn pointplot?

[英]How to add data labels to seaborn pointplot?

下面的代碼創建了一個分類圖,上面有一個點圖,其中點圖顯示了每個類別的均值和 95% 置信區間。 我需要將平均數據標簽添加到圖中,但我不知道該怎么做。

僅供參考,每個類別都有數千個點,所以我不想標記每個數據點,只是點圖中的estimator=np.mean值。 這可能嗎??

我在這里創建了一個示例數據集,因此您可以復制和粘貼代碼並自己運行它。

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

d = {'SurfaceVersion': ['v1', 'v1', 'v1', 'v2', 'v2', 'v2', 'v3', 'v3', 'v3'],
        'Error%': [.01, .03, .15, .28, .39, .01, .01, .06, .09]}

df_comb =  pd.DataFrame(data=d)

plotHeight = 10
plotAspect = 2
 
#create catplot with jitter per surface version:
ax = sns.catplot(data=df_comb, x='SurfaceVersion', y='Error%', jitter=True, legend=False, zorder=1, height=plotHeight, aspect=plotAspect)
ax = sns.pointplot(data=df_comb, x='SurfaceVersion', y='Error%', estimator=np.mean, ci=95, capsize=.1, errwidth=1, hue='SurfaceVersion', color='k',zorder=2, height=plotHeight, aspect=plotAspect, join=False)
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1.0))
plt.gca().legend().set_title('')
plt.grid(color='grey', which='major', axis='y', linestyle='--')
plt.xlabel('Surface Version')
plt.ylabel('Error %')
plt.subplots_adjust(top=0.95, left=.05)
plt.suptitle('Error%')
plt.legend([],[], frameon=False)                #This is to get rid of the legend that pops up with the seaborn plot b/c it's buggy.
plt.axhline(y=0, color='r', linestyle='--')
plt.show()

您可以預先計算平均值並在循環中添加標簽。 請記住,就定位而言,x 值實際上只是 0、1、2。

mean_df = df_comb.groupby("SurfaceVersion")[["Error%"]].mean()

for i, row in enumerate(mean_df.itertuples()):

    x_value, mean = row
    
    plt.annotate(
        round(mean, 2),               # label text
        (i, mean),                    # (x, y)
        textcoords="offset points",   
        xytext=(10, 0),               # (x, y) offset amount
        ha='left')

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM