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

Time:10-23

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()

The Lineplot:

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!

CodePudding user response:

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']],
  • Related