Seaborn条形图与回归线 [英] Seaborn barplot with regression line

查看:128
本文介绍了Seaborn条形图与回归线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在seaborn的x轴包含pandas.Timestamps的条形图中添加回归线?

Is there a way to add a regression line to a barplot in seaborn where the x axis contains pandas.Timestamps?

例如,在下面的此条形图中叠加一条趋势线.我正在寻找最有效的方法来做到这一点:

For example, overlay a trendline in this bar plot below. Am looking for the most efficient way to do this:

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

推荐答案

季节性条形图是分类图.分类图不能直接用于回归,因为数值不适合.但是,通常的matplotlib条形图使用数字数据.

Seaborn barplots are categorical plots. Categorical plots cannot directly be used for regression, because the numeric values would not fit. The usual matplotlib bar plots however use numeric data.

一种选择是在同一张图中绘制matplotlib barplot和seaborn regplot.

An option is to plot a matplotlib barplot and seaborn regplot in the same graph.

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到条形数之间的整数作为indizes,因此也可以将这些indizes用作seaborn条形图之上的回归图.

Since seaborn's barplot uses the integers from 0 to number of bars as indizes, one can also use those indizes for a regression plot on top of seaborn bar plot.

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

这篇关于Seaborn条形图与回归线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆