使用matplotlib创建具有回归线的箱线图

2024-10-02 22:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,其中一列表示“年”,一列表示变量“霜冻日”,每年有多个值。我想创建一个显示每年值分布的箱线图,并添加一条显示50年期间平均霜冻天数变化的回归线。你知道吗

我可以分别创建箱线图和线性回归图,但是我不能让Python在同一个图(在同一个轴上)上同时绘制这两个图。结果应该有大约50个方框图,y轴显示霜冻日,x轴显示年份,根据线性模型,一条回归线穿过方框图。你知道吗

# Create the linear model

x = PRISM_FD_A.year
y = PRISM_FD_A.FrostDays
stats = linregress(x, y)
m = stats.slope
b = stats.intercept
xmin = min(PRISM_FD_A.year)
xmax = max(PRISM_FD_A.year)
ymin = min(PRISM_FD_A.FrostDays)
ymax = max(PRISM_FD_A.FrostDays)
prd = max(PRISM_FD_A.year) - min(PRISM_FD_A.year)
ch = m * prd
ch_FD = ch.astype(int)
string = ("Total Change: %s days over %s years") % (ch_FD, prd)
r = stats.rvalue
r2 = round(((r)**2), 3)
rstring = "R-squared: %s" % r2

# Create the boxplot

ax = PRISM_FD_A.boxplot(by='year',
                       column='FrostDays',
                       grid=False)
ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
plt.show()

Boxplot

# Create the regression line:

fig = plt.figure()
fig.suptitle('Annual Count of Frost Days \n Ashokan Basin', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85, bottom=0.15)
ax.set_title(string, fontsize=10)
ax.set_xlabel("year \n Source:  PRISM", fontsize=10)
ax.set_ylabel("Number of Frost Days", fontsize=10)
ax.plot(a_x, a_m * a_x + a_b, color="red", linewidth=3)
fig.text(0.80, 0.015, rstring, color='white', backgroundcolor='royalblue',
         weight='roman', size='medium')
ax.axis([xmin, xmax, ymin, ymax])
plt.show()

# Join the two together:

fig = plt.figure()
fig.suptitle('Annual Count of Frost Days \n Ashokan Basin', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85, bottom=0.15)
ax.set_xlabel("Year", fontsize=10)
ax.set_ylabel("Number of Frost Days", fontsize=10)
PRISM_FD_A.boxplot(by='year',
                       column='FrostDays',
                       grid=False)
ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
ax.plot(a_x, a_m * a_x + a_b, color="red", linewidth=3)
fig.text(0.80, 0.015, a_rstring, color='white', backgroundcolor='royalblue',
         weight='roman', size='medium')
ax.axis([xmin, xmax, ymin, ymax])
plt.show()

我得到了一个只有回归线的图,没有盒子图。你知道吗

Regression line


Tags: ofthestatsfigpltchaxdays