简体   繁体   中英

Plot A Lineplot with Y-Axis as Percentage (Using PercentFormatter)

I am using the following nested dictionary to make a lineplot:

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}}

While making the lineplot, I want the Y-Axis ticks as the percentage value, for which I'm using 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()

线图:

However, I don't want the default percentage value (as the fig shows). I want the 1st value would be the starting percentage and the subsequent value would be the relative percentage . For example, the 1st plot starts with 200% , which I want as 0% , and the plot ends with 170%, which I want as -something% .

Any suggestions would be appreciated. Thanks!

One way with minor changes to your code is to make the values in y relative to the first value. That is, keep everything as is and replace:

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

with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM