-1

I am trying to change a specific part of the legend in my plot in seaborn.

I wrote the following code to display a plot in seaborn. The plot can be seen below.

ax = sns.lineplot(data = weekly_port_ret,
             x='week',y='R',hue='high_leverage',style='gsector')

ax.set(title='Weekly Portfolio Returns - Daily Rebalancing',
       xlabel='Week in 2020',
       ylabel='Weekly Return'
       )

plt.show()

I am just trying to change where it says "20.0" in the legend to "Industrial", and where it says "45.0" to "IT". Does anyone know how to do this?

My plot:

  • 1
    Map the values in the gsector column of the dataframe to the correct category name. See https://stackoverflow.com/a/41678874/7758804. Managing and cleaning data should occur prior to plotting. – Trenton McKinney Feb 17 '23 at 21:06

1 Answers1

0

You can assign the gsector column to the values (Industrial and IT) and map it so that you can see the legend as you want... Updated code below.

I used some dummy data, but your code should work as well.

Refer assign and map for more info..

mysector = {20:'Industrial', 45:'IT'} 
ax = sns.lineplot(data = weekly_port_ret.assign(gsector=weekly_port_ret['gsector'].map(mysector)),
             x='week',y='R',hue='high_leverage',style='gsector')

ax.set(title='Weekly Portfolio Returns - Daily Rebalancing',
       xlabel='Week in 2020',
       ylabel='Weekly Return'
       )

plt.show()

Plot

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26