【问题标题】:Plot A Lineplot with Y-Axis as Percentage (Using PercentFormatter)绘制以 Y 轴为百分比的线图(使用 PercentFormatter)
【发布时间】:2021-12-09 10:23:12
【问题描述】:

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

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

但是,我不想要默认的百分比值(如图所示)。我希望1st valuestarting percentage,随后的值是relative percentage。例如,第一个情节以200% 开头,我想要0%,情节以170%, 结尾,我想要-something%

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

【问题讨论】:

    标签: python pandas matplotlib plot seaborn


    【解决方案1】:

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

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

    与:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2015-05-17
      • 1970-01-01
      • 2020-06-01
      • 2023-03-15
      • 1970-01-01
      • 2013-12-27
      相关资源
      最近更新 更多