python - 需要使用 matplotlib 在数据框的折线图上标记随时间变化的百分比
问题描述
我使用以下代码创建了两个图表。我需要计算每个数据点的百分比变化并将其标记在行上(例如“+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()
解决方案
由于没有参数来显示名称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()
我正在注释掉一段代码以在我的环境中显示图表。这些问题是手动创建的,因为没有数据就无法检查它们。下次请提供非图片的数据。
推荐阅读
- r - 如何用 R 语言为不同的数据集编写函数方差分析?
- swift - 快速将数据发送到 Firestore 数据库时出现问题
- sql - postgresql / plpgsql - 具有循环和多个动作的函数
- html - 如何通过css选择所有输入元素?
- python - 如何通过 Python 中的令牌向 API 授权
- pdo - 如何正确地将我的变量绑定到我的令牌?
- html - 溢出:隐藏在我的幻灯片项目中不起作用
- python-3.x - 如何在 Python 中使用内部字典解析复杂列表
- python - LSTM RNN 同时预测多个时间步长和多个特征
- google-cloud-platform - 有没有办法在 GCP 上将 gsutil 作为常规 Linux cronjob 运行?