我正在与seaborn合作,并试图使条形图看起来更好。

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)


python - Seaborn的条形图-LMLPHP

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

我的问题是,在正面上标记为负的那条。我也想摆脱每个图的开头的零,并可能将x = ['One','Two','Three','Four','Five']移到零所在的中间,而不是放在底部。

最佳答案

这是您只需要对barplot进行一次调用并将注解放置在x轴正确侧的逻辑

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)


python - Seaborn的条形图-LMLPHP

关于python - Seaborn的条形图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32528154/

10-16 18:45