Search code examples
pythonmatplotlibseabornyaxis

How to use mapped values for numerical chart axis ticks


Say I have a variable, df, that contains some data that looks like this in pandas

Date          Number Letter
2017-10-31    2      B
2019-08-31    1      A
2021-11-30    3      C
...

I'd like to chart this out in seaborn, so I use some code like this

sb.lineplot(data=df, x=Date, y=Number)
plt.show()

And I get an orderly line chart that looks something like this enter image description here

However, i'd like to have the y axis tick labels to preserve the numerical order of the number column, but present as labels from the letter column. For instance, instead of the y axis being 10 - 17 as above, i'd like the y axis to read j - t.

Is there a way to implement that through the sb.lineplot arguments, or would I need another way?


Solution

  • IIUC, you can use FixedLocator and FixedFormatter:

    import matplotlib.ticker as ticker
    
    ax = sb.lineplot(data=df, x='Date', y='Number')
    ax.yaxis.set_major_locator(ticker.FixedLocator(df['Number']))
    ax.yaxis.set_major_formatter(ticker.FixedFormatter(df['Letter']))
    plt.show()
    

    Output:

    enter image description here