[Python] plotting vertical lines on pandas line plot with multiindex x axis

Discussão em 'Python' iniciado por Stack, Março 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataframe whose index is a multiindex where axes[0] is the date, and axis[1] is the rank. Rank starts with 1 and ends at 100, but there can be a variable number of ranks in between as below.

    index​
    value
    (date1, rank 1)​
    2.3
    (date1, rank 2)​
    2.5
    (date1, rank 3)​
    2.4
    (date1, rank 100)​
    2.36
    (date2, rank 1)​
    2.165
    (date2, rank 2)​
    2.54
    (date2, rank 100)​
    2.34
    (date3, rank 1)​
    2.12
    (date3, rank 2)​
    2.32
    (date3, rank 3)​
    2.43
    (date3, rank 4)​
    2.4
    (date3, rank 100)​
    2.3​

    I want to plot this df, and df.plot() works fine creating a reasonable x-axis. However, I want to add a grid or vertical lines at all the rank=1, and all the rank=100(different color).

    I tried this :

    xs = [x for x in df.index if x[1]==1]
    for x in xs:
    ax.axvline(x=x, color ='red')


    but get this error:

    Failed to convert value(s) to axis units : (Timestamp('2025-02-24 00:00:00'), 1.0)


    I also want to only show x labels for rank=1, and not all of them. Currently, if i set label rotation to 90, it results in that but not sure if this is the best way to ensure that.

    ax.tick_params('x', labelrotation=90)


    So looking for 2 answers

    1. How to set vertical lines at specific points with this type of multiindex
    2. How to ensure only certain x labels show on the chart

    Continue reading...

Compartilhe esta Página