seaborn 中的条形图 [英] Bar chart in seaborn

查看:56
本文介绍了seaborn 中的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与 seaborn 合作,并试图让我的条形图看起来更好.

I am working with seaborn, and trying to make my bar chart look better.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

x = ['One', 'Two', 'Three', 'Four', 'Five']
y = [2, 3, 0, 4.5, 4]
y2 = [0, 0, -5, 0, 0]

sns.axes_style('white')
sns.set_style('white')

b = sns.barplot(x,y,color='pink')
sns.barplot(x,y2, color='red')

for p in b.patches:
    b.annotate(
        s='{:.1f}'.format(p.get_height()),
        xy=(p.get_x()+p.get_width()/2.,p.get_height()),
        ha='center',va='center',
        xytext=(0,10),
        textcoords='offset points'
)

b.set_yticks([])
sns.despine(ax=b, left=True, bottom=True)

实际上,我在堆栈溢出时使用了用于标记来自另一个线程的钢筋的代码.

I actually took code for labelling bars from another thread on stack overflow.

我遇到的问题是,消极的条形被标记在积极的一面.我还想摆脱每个图形开头的零,并可能将 x = ['One','Two','Three','Four','五个'] 移动到零在中间,而不是在底部.

The problem I have that the bar that is negative being labeled on the positive side. I also want to get rid of zeros at the beginning of each graph, and possibly move x = ['One','Two','Three','Four','Five'] in the middle where zeros are, instead of it being on the bottom.

推荐答案

这里的逻辑是您只需调用 1 次 barplot 并将注释放在 x 轴的正确一侧

Here's the logic you need make only 1 call to barplot and place the annotation on the correct side of the x-axis

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

x = ['One', 'Two', 'Three', 'Four', 'Five']
y = [2, 3, -5, 4.5, 4]

sns.axes_style('white')
sns.set_style('white')

colors = ['pink' if _y >=0 else 'red' for _y in y]
ax = sns.barplot(x, y, palette=colors)

for n, (label, _y) in enumerate(zip(x, y)):
    ax.annotate(
        s='{:.1f}'.format(abs(_y)),
        xy=(n, _y),
        ha='center',va='center',
        xytext=(0,10),
        textcoords='offset points',
        color=color,
        weight='bold'
    )

    ax.annotate(
        s=label,
        xy=(n, 0),
        ha='center',va='center',
        xytext=(0,10),
        textcoords='offset points',
    )  
# axes formatting
ax.set_yticks([])
ax.set_xticks([])
sns.despine(ax=ax, bottom=True, left=True)

这篇关于seaborn 中的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆