【发布时间】:2019-08-01 08:14:31
【问题描述】:
我有一个数据框,其中有一列用于“年”,一列用于变量“FrostDays”,每年都有多个值。我想创建一个显示每年值分布的箱线图,并添加一条回归线,显示 50 年期间 FrostDays 平均数的变化。
我可以分别创建箱线图和线性回归图,但我无法让 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()
我得到一个只有回归线而没有箱线图的图。
【问题讨论】:
标签: python pandas matplotlib