我有一个数据框,其中有一个“年份”列和一个变量“ FrostDays”列,每年都有多个值。我想创建一个箱形图,以显示每年值的分布,并添加一条回归线以显示50年内FrostDays平均数量的变化。
我可以分别创建boxplot和线性回归图,但是我无法让Python在同一图形(同一轴)上同时绘制两者。结果应具有约50个箱形图,其中y轴显示FrostDays,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()
# 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()
我得到的图只有回归线,没有箱形图。
答案 0 :(得分:0)
您需要使用pandas
为ax=ax
箱形图指定图形轴。
PRISM_FD_A.boxplot(by='year',column='FrostDays',ax=ax,grid=False)