首页 > 解决方案 > 绘制以 Y 轴为百分比的线图(使用 PercentFormatter)

问题描述

我正在使用以下嵌套字典来制作线图:

df = {'A': 
     {'weight': [200, 190, 188, 180, 170],
     'days_since_gym': [0, 91, 174, 205, 279],
     'days_since_fasting': 40},
     'B': 
     {'weight': [181, 175, 172, 165, 150],
     'days_since_gym': [43, 171, 241, 273, 300],
     'days_since_fasting': 100}}

在制作线图时,我希望将Y-Axis刻度作为percentage我正在使用的值PercentFormatter

# set the plot size
fig, ax = plt.subplots(2, figsize=(10, 6))

for i, x in enumerate(df.keys()):    
    sns.lineplot(
        x=df[x]['days_since_gym'],
        y=df[x]['weight'],
        marker="o",
        ax=ax[i],
    )
    
    ax[i].axvline(df[x]['days_since_fasting'], color='k', linestyle='--', label='Fasting Starts')
    ax[i].set_xlim(left=0, right=365)
    
    # Percentage y-axis
    ax[i].yaxis.set_major_formatter(mtick.PercentFormatter())

plt.xlabel('Days Since Joined Gym')
plt.ylabel('Relastive Weight')
plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
plt.show()

线图:

但是,我不想要默认的百分比值(如图所示)。我希望 the1st value是 thestarting percentage并且后续值是 the relative percentage。例如,第一个情节以200%我想要的开头,情节以我想要0%的结尾。170%,-something%

任何建议,将不胜感激。谢谢!

标签: pythonpandasmatplotlibplotseaborn

解决方案


对代码进行细微更改的一种方法是使值y相对于第一个值。也就是说,保持一切原样并替换:

y=df[x]['weight'],

和:

y=[a-df[x]['weight'][0] for a in df[x]['weight']],

推荐阅读