2015-09-11 24 views
1

我与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) 

enter image description here

我竟拿出了标签栏的代码从堆栈溢出另一个线程。

我有即负杆被标记在正侧的问题。我也想在每张图的开始处摆脱零,并且可能将x = ['One','Two','Three','Four','Five']移动到零的中间,而不是在底部。

+0

我认为你的主要问题是你打电话给barplot两次。找到一种将它压缩到一个通话的方式可能会有很大的帮助。此外,请提供您用于通知此帖的问题的链接。 –

+0

你应该尝试限制这只是一个问题。我现在回答最后一个:'sns.despine(ax = b,bottom = True,left = True)'将摆脱框架。 –

+0

你得到的'0.0'的,因为你通过所有的补丁的循环,所以你需要包括不标注一个条件时,p.get_height的'值()'不大于零。 –

回答

3

这里有您需要做只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) 

enter image description here

+0

无需两次调用'barplot';刚刚过去想要作为调色板的颜色列表。 – mwaskom

+1

此外,对于这种情节,从数据对象中获取比从轴出来的条高度要简单得多。 – mwaskom

+0

是的。删除了额外的电话,但选择绘图后设置条形颜色。我想根据这些数据生成一个调色板会很容易。但是,既然我们正在通过酒吧循环,可能不值得。 –

0

感谢大家的意见的逻辑。 这是我的解决方案: 我已将负数移到列表的末尾。 (尽管没有那么大的差距)

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')