【问题标题】:Centre bars in barplots if category is missing in hue如果色调中缺少类别,则条形图中的中心条
【发布时间】:2021-11-08 04:08:34
【问题描述】:

如果有人在 seaborn 的条形图中使用 hue 并且缺少其中一个类别,则会导致这种“空列”的奇怪效果,其中 seaborn 在预期色调的位置没有任何内容(见下文第二个位置,星期五;或在第二张图片中)。一个人怎么能把这种情况集中起来,让它在勾号的地方呢?在第一种情况下,它将位于橙色条的中间,在第二种情况下,它将删除蓝色和绿色之间的空白区域并将刻度线放在绿色条的中间。 谢谢。

import seaborn

tips = sns.load_dataset("tips")
tips.loc[(tips["sex"]=="Male")&(tips["day"]=="Fri"), "total_bill"]=np.nan

sns.barplot(x="day", y="total_bill", hue="sex", data=tips)

sns.barplot(x="sex", y="total_bill", hue="day", data=tips)

旁注,与post无关。

【问题讨论】:

标签: python matplotlib seaborn bar-chart


【解决方案1】:

正如@TrentonMcKinney 在 cmets 中提到的,following post 有一些手动解决方法(已更改和调整,还请注意,颜色会保留,因为它不接触图表,只是位置):

import seaborn
tips = sns.load_dataset("tips")
tips.loc[(tips["sex"]=="Male")&(tips["day"]=="Fri"), "total_bill"]=np.nan

plot1 = sns.barplot(x="day", y="total_bill", hue="sex", data=tips)

for i, bar in enumerate(plot1.axes.patches): 

    # move the missing to the centre
    current_width = bar.get_width()
    current_pos = bar.get_x()
    if i == 5:
        bar.set_x(current_pos-(current_width/2))
        # move also the std mark
        plot1.axes.lines[i].set_xdata(current_pos)


plot2 = sns.barplot(x="sex", y="total_bill", hue="day", data=tips)

for i, bar in enumerate(plot2.axes.patches): 

    # move the missing to the centre
    current_width = bar.get_width()
    current_pos = bar.get_x()
    if i == 0:
        bar.set_x(current_pos+(current_width/2))
        # get also the std mark
        plot2.axes.lines[i].set_xdata(current_pos+(current_width))
    
    if i == 4:
        bar.set_x(current_pos-(current_width/2))
        # get also the std mark
        plot2.axes.lines[i].set_xdata(current_pos)
    
    if i == 6:
        bar.set_x(current_pos-(current_width/2))
        # get also the std mark
        plot2.axes.lines[i].set_xdata(current_pos)    

还有更多的工作(例如,还要处理 std 或找到正确的索引),但问题仍然存在——它填充了空间,使其看起来更好,但不会删除空间。但是,我相信这已经足够了。非常感谢@JohanC 和@TrentonMcKinney。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-09-17
    • 2020-12-07
    • 2013-12-24
    相关资源
    最近更新 更多