How to annotate end of lines using python and matplotlib?

前端 未结 2 2087
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 12:10

With a dataframe and basic plot such as this:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123456)
rows = 75
df = p         


        
2条回答
  •  有刺的猬
    2020-11-28 12:52

    Method 1

    Here is one way, or at least a method, which you can adapt to aesthetically fit in whatever way you want, using the plt.annotate method:

    [EDIT]: If you're going to use a method like this first one, the method outlined in ImportanceOfBeingErnest's answer is better than what I've proposed.

    df.plot()
    
    for col in df.columns:
        plt.annotate(col,xy=(plt.xticks()[0][-1]+0.7, df[col].iloc[-1]))
    
    plt.show()
    

    For the xy argument, which is the x and y coordinates of the text, I chose the last x coordinate in plt.xticks(), and added 0.7 so that it is outside of your x axis, but you can coose to make it closer or further as you see fit.

    METHOD 2:

    You could also just use the right y axis, and label it with your 3 lines. For example:

    fig, ax = plt.subplots()
    df.plot(ax=ax)
    ax2 = ax.twinx()
    ax2.set_ylim(ax.get_ylim())
    ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
    ax2.set_yticklabels(df.columns)
    
    plt.show()
    

    This gives you the following plot:

提交回复
热议问题