-1

My question goes as follows:

Imagine I have four lists a, b, c, d. I want to plot them by using the same radial grid R. For some reason a, b share a common property X and c, d share Y. Therefore I want a, b and c, d to appear in the same color respectively (green and blue), and I just want two labels to appear into the legend: one being green and resembling X and the other blue and resembling Y. Any ideas of a simple method to do it? An example:

import matplotlib.pyplot as plt

a =[2,4,6,8,10]
b =[3,6,9,12,15]
c =[1,4,9,16,25]
d =[1,8,27,64,125]
R =[0,1,2,3,4]

plt.plot(R,a,color ='green')
plt.plot(R,b,color ='green')
plt.plot(R,c,color ='blue')
plt.plot(R,d,color ='blue')
plt.legend('blue'= X,'green'=Y)
plt.show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Berni
  • 551
  • 10
  • 17

1 Answers1

2

You can label only the objects you want to display in the legend once instead of manually setting the legends as following. I also replaced color ='green' by a shorter syntax '-g', same for the blue color.

# Your imports and data here

plt.plot(R,a,'-g', label='X')
plt.plot(R,b,'-g')
plt.plot(R,c,'-b', label='Y')
plt.plot(R,d,'-b')
plt.legend(fontsize=18)
plt.show()

enter image description here

Alternate way Without putting label='X' and label='Y' while plotting

leg = plt.legend(['X', 'Y'], fontsize=18)
colors=['green', 'blue']

for i, j in enumerate(leg.legendHandles):
    j.set_color(colors[i])
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Sure! Thanks , i don't know why i was thinking about a more complicated answer. – Berni Oct 03 '18 at 18:22
  • You are welcome. I edited your question because you wrote green for Y and blue for X, but you used other way round in your code. – Sheldore Oct 03 '18 at 18:23
  • Strange that people go downvoting for no reason. – Sheldore Oct 03 '18 at 18:33
  • I realized would need a more general way to do it ( if there is one) . My example is just a simplified version of my problem . On reality i am dealing with an interface with several plots and buttons involved, and I have loop where i perform the plots inside. Then it comes the problem , namely that i can not set the legend just once. – Berni Oct 03 '18 at 18:37
  • Perhaps you need to add more details to your question – Sheldore Oct 03 '18 at 18:40
  • Alternative way just created one legend on plot for me and then I solved this via making patches for each label and color as explained here: https://stackoverflow.com/questions/39500265/how-to-manually-create-a-legend – Celuk Oct 04 '22 at 15:54