首页 > 解决方案 > 需要使用 matplotlib 在数据框的折线图上标记随时间变化的百分比

问题描述

我有一个名为 megobi2 的数据框。 在此处输入图像描述

我使用以下代码创建了两个图表。我需要计算每个数据点的百分比变化并将其标记在行上(例如“+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()

在此处输入图像描述

标签: pythonpandasmatplotlibpandas-groupby

解决方案


由于没有参数来显示名称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()

在此处输入图像描述

我正在注释掉一段代码以在我的环境中显示图表。这些问题是手动创建的,因为没有数据就无法检查它们。下次请提供非图片的数据。


推荐阅读