Python Seaborn条形图-显示值时不一致

Python Seaborn条形图-显示值时不一致,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,对于Seaborn中的多组条形图,我想在每个条形图的顶部添加从int\u txt引用的文本。 但是,文本未按预期放置 例如,下面的代码 import seaborn as sns import pandas as pd from matplotlib import pyplot as plt # Create an example dataframe data = {'pdvalue': [1, 1, 1, 1, 4, 4, 4, 4, 2, 2, 2, 2, 8, 8, 8, 8],

对于Seaborn中的多组条形图,我想在每个条形图的顶部添加从
int\u txt
引用的文本。 但是,文本未按预期放置

例如,下面的代码

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


# Create an example dataframe
data = {'pdvalue': [1, 1, 1, 1, 4, 4, 4, 4, 2, 2, 2, 2, 8, 8, 8, 8],
        'xval': [0, 0, 0.5, 0.5, 0.2, 0, 0.2, 0.2, 0.3, 0.3, 0.4, 0.1, 1, 1.1, 3, 1],
        'int_txt': [11, 14, 4, 5.1, 1, 2, 5.1, 1, 2, 4, 1, 3, 6, 6, 2, 3],
        'group': ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']}
df = pd.DataFrame(data)

df['int_txt'] = df['int_txt'].round(0).astype(int)
df=df.sort_values(by='pdvalue', ascending=True)
g = sns.barplot (data=df,x="pdvalue",y="xval",hue="group",)

for idx,p in enumerate(g.patches):
    if p.get_height()!=0:
        val_me=df['int_txt'][idx]
        g.annotate(format(val_me, '.1f'),
                       (p.get_x() + p.get_width() / 2., p.get_height()),
                       ha = 'center', va = 'center',
                       xytext = (0, 9),
                       textcoords = 'offset points')
plt.show()
遗嘱产生

然而,预期输出应如下所示:

附加文本基于查找表

对于任何等于零的
xval
,将不追加任何文本


我可以知道我哪里做错了吗?

你真的没有做错什么。它只不过是先按色调绘制条。要看到这一点,请执行以下操作:

for idx,p in enumerate(g.patches):
    # annotate the enumeration
    g.annotate(format(idx, '.1f'),
                   (p.get_x() + p.get_width() / 2., p.get_height()),
                   ha = 'center', va = 'center',
                   xytext = (0, 9),
                   textcoords = 'offset points')
您可以看到(注意顶部的枚举)

一种方法是按
hue
列对数据进行排序,然后使用
.iloc
进行访问:

# sort by group first
df=df.sort_values(by=['group','pdvalue'], ascending=True)

g = sns.barplot (data=df,x="pdvalue",y="xval",hue="group",)
for idx,p in enumerate(g.patches):
    if p.get_height()!=0:
        # access with `iloc`, not `loc`
        val_me=df['int_txt'].iloc[idx]
        g.annotate(format(val_me, '.1f'),
                   (p.get_x() + p.get_width() / 2., p.get_height()),
                   ha = 'center', va = 'center',
                   xytext = (0, 9),
                   textcoords = 'offset points')
您将得到预期的注释: