2017-06-04 95 views
0

有没有方法可以将回归线添加到x轴包含pandas的seaborn中的barplot中。时间戳?有回归线的Seaborn barplot

例如,在下面的条形图中覆盖趋势线。在寻找最有效的方式做到这一点:

seaborn.set(style="white", context="talk") 
a = pandas.DataFrame.from_dict({'Attendees': {pandas.Timestamp('2016-12-01'): 10, 
    pandas.Timestamp('2017-01-01'): 12, 
    pandas.Timestamp('2017-02-01'): 15, 
    pandas.Timestamp('2017-03-01'): 16, 
    pandas.Timestamp('2017-04-01'): 20}}) 
ax = seaborn.barplot(data=a, x=a.index, y=a.Attendees, color='lightblue',) 
seaborn.despine(offset=10, trim=False) 
ax.set_ylabel("") 
ax.set_xticklabels(['Dec', 'Jan','Feb','Mar','Apr']) 
plt.show() 

enter image description here

+0

相关,但没有确切的重复:https://stackoverflow.com/questions/40558128/using-datetimes-with-seaborns-regplot – ImportanceOfBeingErnest

回答

3

Seaborn barplots是绝对的地块。分类图不能直接用于回归,因为数值不适合。然而,通常的matplotlib条形图却使用数字数据。

一个选项是在同一个图中绘制matplotlib barplot和seaborn regplot。

import numpy as np; np.random.seed(1) 
import seaborn.apionly as sns 
import matplotlib.pyplot as plt 

x = np.linspace(5,9,13) 
y = np.cumsum(np.random.rand(len(x))) 

fig, ax = plt.subplots() 

ax.bar(x,y, width=0.1, color="lightblue", zorder=0) 
sns.regplot(x=x, y=y, ax=ax) 
ax.set_ylim(0, None) 
plt.show() 

enter image description here

由于seaborn的barplot使用从0整数为indizes的条数,还可以使用那些indizes对seaborn条形图顶部的回归图。

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

sns.set(style="white", context="talk") 
a = pandas.DataFrame.from_dict({'Attendees': {pandas.Timestamp('2016-12-01'): 10, 
    pandas.Timestamp('2017-01-01'): 12, 
    pandas.Timestamp('2017-02-01'): 15, 
    pandas.Timestamp('2017-03-01'): 16, 
    pandas.Timestamp('2017-04-01'): 20}}) 
ax = sns.barplot(data=a, x=a.index, y=a.Attendees, color='lightblue') 
# put bars in background: 
for c in ax.patches: 
    c.set_zorder(0) 
# plot regplot with numbers 0,..,len(a) as x value 
sns.regplot(x=np.arange(0,len(a)), y=a.Attendees, ax=ax) 
sns.despine(offset=10, trim=False) 
ax.set_ylabel("") 
ax.set_xticklabels(['Dec', 'Jan','Feb','Mar','Apr']) 
plt.show() 

enter image description here

+0

谢谢你的解释 - 是有道理的。我想要做的是显示一个按月出席的条形图,并覆盖回归线。我可能没有使用正确的图表类型。你有推荐吗? – CarlosE

+0

那么,我的建议是上述解决方案。如果这对你没有帮助,你需要分享你想要的东西。 – ImportanceOfBeingErnest

+0

这是个窍门。鉴于这是一个非常常见的用例,我曾希望有一种直接的方法可以用regplot参数来做到这一点,而不必“掩盖”索引的性质或设置zorders。 – CarlosE