seaborn 中的条形图

Bar chart in seaborn

我正在使用 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)

我实际上是在堆栈溢出时从另一个线程获取了用于标记条形图的代码。

我遇到的问题是负条被标记在正侧。我还想去掉每个图表开头的零,并可能将 x = ['One','Two','Three','Four','Five'] 移动到零所在的中间,而不是在底部。

这是您只需要调用 1 次 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)

感谢大家的评论。 这是我的解决方案: 我已将负数移至列表末尾。 (虽然差别不大)

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

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

figure()
sns.axes_style('white')
b = sns.barplot(x,y2, color='red')

for z in b.patches[4:5]:
    b.annotate(np.round(-z.get_height(),decimals=6),(z.get_x()+z.get_width()/2.,-z.get_height()),ha='center',va='center',xytext=(0,10),textcoords='offset points', color='w')   

b=sns.barplot(x,y, color='blue')
for p in b.patches[5:9]:
    b.annotate(np.round(p.get_height(),decimals=6),(p.get_x()+p.get_width()/2.,p.get_height()),ha='center',va='center',xytext=(0,-10),textcoords='offset points', color='w')

仅供参考:AK9309 的最终回答在我的设置中产生了以下图 (python 2):