我使用以下代码创建了两个图形。我需要计算每个数据点的变化百分比,并将其标记在行上(例如“ +20%”)。
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, (1,3))
ax2 = fig.add_subplot(2, 2, (2,4))
x = [datetime.datetime(2020, 5, 1), datetime.datetime(2020, 5, 15),
datetime.datetime(2020, 6, 1), datetime.datetime(2020, 6, 15), datetime.datetime(2020, 6, 30),]
megobi2.groupby('Name').plot(x='Date', y='BMI', ax=ax1, legend=False)
#ax1.set_ylim((5,5))
ax1.yaxis.set_ticks([24, 26, 28])
ax1.xaxis.set_ticks(x)
#ax1.xaxis.set_label_text("Date")
ax1.set_title("BMI over time")
megobi2.groupby('Name').plot(x='Date', y='Weight', ax=ax2, legend=False)
ax2.yaxis.set_ticks([150, 155, 160, 170, 175, 180, 185])
ax2.xaxis.set_ticks(x)
#ax2.xaxis.set_label_text("Date")
ax2.set_title("Weight over time")
plt.subplots_adjust(left=1.3, right=2.3, bottom=0.1, top=0.5)
fig.subplots_adjust(wspace=.6)
plt.show()
答案 0 :(得分:0)
由于df.plot
中没有显示名称的参数,因此我们必须从数据框中创建一个新名称。必要项通过groupby
获得。所获取的文本将与ax.annotate()
添加在一起。
txt = megobi2.groupby(['Name'])[['Weight','BMI']].agg(np.mean)
txt
Weight BMI
Name
Megan 156.600000 26.885714
Obi 177.857143 24.757143
代码:
import matplotlib.pyplot as plt
import datetime
fig = plt.figure(figsize=(8,3),dpi=144)
ax = fig.add_subplot(121)
# fig = plt.figure()
ax1 = fig.add_subplot(2, 2, (1,3))
ax2 = fig.add_subplot(2, 2, (2,4))
x = [datetime.datetime(2020, 5, 1), datetime.datetime(2020, 5, 15),
datetime.datetime(2020, 6, 1), datetime.datetime(2020, 6, 15), datetime.datetime(2020, 6, 30),]
megobi2.groupby('Name').plot(x='Date', y='BMI', ax=ax1, legend=False)
# ax1.set_ylim((5,5))
# ax1.yaxis.set_ticks([24, 26, 28])
# ax1.xaxis.set_ticks(x)
# ax1.xaxis.set_label_text("Date")
ax1.set_title("BMI over time")
t3 = ax1.annotate(txt.loc[txt['BMI'] == txt['BMI'].max()].index[0], (0.5,txt['BMI'].max()-5/100))
t4 = ax1.annotate(txt.loc[txt['BMI'] == txt['BMI'].min()].index[0], (0.5,txt['BMI'].min()+5/100))
print(t3,t4)
megobi2.groupby('Name').plot(x='Date', y='Weight', ax=ax2, legend=False)
# ax2.yaxis.set_ticks([150, 155, 160, 170, 175, 180, 185])
# ax2.xaxis.set_ticks(x)
#ax2.xaxis.set_label_text("Date")
ax2.set_title("Weight over time")
t1 = ax2.annotate(txt.loc[txt['Weight'] == txt['Weight'].max()].index[0], (0.2,txt['Weight'].max()-5))
t2 = ax2.annotate(txt.loc[txt['Weight'] == txt['Weight'].min()].index[0], (0.2,txt['Weight'].min()+5))
print(t1,t2)
plt.subplots_adjust(left=1.3, right=2.3, bottom=0.1, top=0.5)
fig.subplots_adjust(wspace=.6)
plt.show()
我正在注释掉一部分代码,以在我的环境中显示图形。 这些问题是手动创建的,因为没有数据就无法检查它们。 下次,请提供非图像数据。