You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Seaborn条形图添加数值标签及水平条形图报错解决

Let's work through your two pandas/seaborn issues step by step:

1. Fixing the horizontal bar chart error

The TypeError you're hitting happens because when using orient='h' (horizontal bars), you need to swap the x and y arguments. Seaborn expects the numeric variable to be assigned to x and the categorical variable to y for horizontal bars—your original code had them reversed, which caused type mismatches during plotting.

Also, note that factorplot is deprecated in newer seaborn versions; it’s recommended to use catplot instead (it’s just a renamed, maintained version of the same function). Here’s the corrected code:

import seaborn as sns
import pandas as pd

temp = pd.DataFrame({'country':['A1','A1','A1','A1','A2','A2','A2','A2'], 
                     'seg': ['S1','S2','S1','S2','S1','S2','S1','S2'], 
                     'agegroup': ['1', '2', '2', '1','1', '2', '2', '1'], 
                     'N' : [21,22,23,24,31,32,33,34]})

# Swap x and y, use orient='h', and use catplot instead of factorplot
g = sns.catplot(data=temp, x='N', y='seg', hue='agegroup', row='country', 
                kind='bar', orient='h', legend=True, aspect=1)
2. Adding value labels to each bar

To add the exact N values at the end of each horizontal bar, you’ll need to iterate over each axis in the FacetGrid and each bar container within those axes. Modern matplotlib has a built-in bar_label function that simplifies this:

# After creating the FacetGrid `g`
for ax in g.axes.flat:
    # Iterate through each group of bars in the axis
    for container in ax.containers:
        # Add labels to the edge of each bar
        ax.bar_label(container, label_type='edge')

# Adjust layout to prevent label cutoff
g.tight_layout()

If you’re using an older matplotlib version where bar_label isn’t available, you can manually calculate label positions:

for ax in g.axes.flat:
    for p in ax.patches:
        # Get the bar's width (numeric value) and vertical center position
        bar_width = p.get_width()
        bar_y_center = p.get_y() + p.get_height() / 2
        # Add the text label with slight offset for readability
        ax.text(bar_width + 0.5, bar_y_center, f'{int(bar_width)}', 
                ha='left', va='center')

This will place the N value clearly at the end of every horizontal bar, making your chart more informative.


内容的提问来源于stack exchange,提问作者quant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:30:21