-2

I would like to label the lines of my plots on a secondary y-axis to the right of my plot, with the label of each line at the height of its final point, as well as the color of that line as shown in this image in matplotlib.

image

I have tried using an annotate solution based on this answer, however this places the label inside of the plot and overlaps for certain points.

import matplotlib.pyplot as plt
import numpy as np

l = ['label {:d}'.format(i) for i in range(1,5)]

x = [0,1]
yy = np.transpose([np.arange(1,5),np.arange(1,5)])
l2 = 'overlap'
y2 = [3.95,3.95]

fig, ax = plt.subplots()
for y,l in zip(yy,l):
    ax.plot(x,y)
    ax.annotate(xy=(x[-1],y[-1]), xytext=(20,0), textcoords='offset points', text=l, va='center')
    
ax.plot(x,y2)
ax.annotate(xy=(x[-1],y2[-1]), xytext=(20,0), textcoords='offset points', text=l2, va='center')

plt.show()


I am assuming there is a better way to accomplish this goal, could you please point me towards a solution?

Edited sample code to highlight specific overlap issue.

  • the question needs sufficient code for a minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example – D.L Oct 01 '22 at 11:41

1 Answers1

-1

Try to tune the x,y parameters in the xytext=(x,y).

import matplotlib.pyplot as plt
import numpy as np

l = ['label {:d}'.format(i) for i in range(1,5)]

x = [0,1]
yy = np.transpose([np.arange(1,5),np.arange(1,5)])
l2 = 'overlap'
y2 = [3.95,3.95]

fig, ax = plt.subplots()
for y,l in zip(yy,l):
    ax.plot(x,y)
    ax.annotate(xy=(x[-1],y[-1]), xytext=(20,0), textcoords='offset points', text=l, va='center')
    
ax.plot(x,y2)
ax.annotate(xy=(x[-1],y2[-1]), xytext=(20,-5), textcoords='offset points', text=l2, va='center')

plt.show()

enter image description here

Li Yupeng
  • 721
  • 4
  • 9
  • Thank you that allowed me to place the labels outside of the plot. In my use case however, I have points which are much closer together (e.g. 4.8 and 4.7) causing the labels to overlap. How can I resolve this with even spacing, as shown in the image? – Alpha_Ursae_Minoris Oct 01 '22 at 13:55
  • 1
    I don't have the code and data for your real case, I can not tune it. – Li Yupeng Oct 01 '22 at 14:00
  • I have updated the minimal reproducible example to highlight the vertical overlap issue that remains. – Alpha_Ursae_Minoris Oct 01 '22 at 17:45