Python 带回归线的Seaborn条形图
有没有办法在seaborn的条形图中添加回归线,其中x轴包含熊猫。时间戳 例如,在下面的条形图中覆盖趋势线。我正在寻找最有效的方法:Python 带回归线的Seaborn条形图,python,matplotlib,regression,bar-chart,seaborn,Python,Matplotlib,Regression,Bar Chart,Seaborn,有没有办法在seaborn的条形图中添加回归线,其中x轴包含熊猫。时间戳 例如,在下面的条形图中覆盖趋势线。我正在寻找最有效的方法: 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('
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()
Seaborn条形图是分类图。分类图不能直接用于回归,因为数值不合适。但是,通常的matplotlib条形图使用数字数据 一个选项是在同一图形中绘制matplotlib条形图和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()
由于seaborn的条形图使用从0到条数的整数作为索引,因此也可以将这些索引用于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()
谢谢您的解释-很有道理。我想做的是显示一个条形图,每个月的出勤率,并叠加一条回归线。我可能没有使用正确的图表类型。你有什么建议吗?嗯,我的建议就是上面的解决方案。如果这对你没有帮助,你需要与别人分享你想要的东西。这样做很有效。考虑到这是一个非常常见的用例,我曾希望有一种简单的方法可以使用regplot参数实现这一点,而不必“屏蔽”索引的性质或设置zorder。我想每个人都认为他的特殊用例“非常常见”。-)是的!非常感谢-非常感谢@ImportanceOfBeingErnest顺便说一句,我特别喜欢王尔德和那出戏(“认真”)。相关,但没有确切的副本: