0

The answer to this question seems to suggest that one way to set legend font properties is through the following:

     import pylab as plt
     leg = plt.legend(framealpha = 0, loc = 'best')
     for text in leg.get_texts():
              plt.setp(text, color = 'w')

Which requires a call to plt.legend() and collects all the legends and does not distinguish between certain specific legends. In my code, I have several different plots. For example, dicts1 and dicts2 are dictionaries that contain dataframes:

def compare_data(dicts1, dicts2):
    for dic in dicts1:
       df = dic['df']
       style = dic['style'] 
       plt.plot(df['time'], df['y'], **style)   
       ## style contains the legend text
       ## use the default font

     for dic in dicts2:
       df = dic['df']
       style = dic['style']
       plt.plot(df['time'], df['y'], **style)
       ## only modify the font color for the legends of these !!

     # finally draw the legend with the common properties:
     plt.legend(loc = 'best', frameon=False)

How do I modify the font color for the legends of only dict2 and not dict1 ? The values of legend color for dict1 remain as default values. The number of elements in both dictionaries is arbitrary.

wander95
  • 1,298
  • 1
  • 15
  • 22
  • What exactly is your question? I don't see any question in your whole post. Once you figure out exactly what your problem is, please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Sheldore Jun 19 '19 at 20:53
  • The question is in the comment. Sorry. I will explicitly add the question – wander95 Jun 19 '19 at 20:54
  • Yes, I see that. But how is it related to your second code? What is the desired behavior? What is the final output required? Where is the runnable code? Please read the link in my first comment. – Sheldore Jun 19 '19 at 20:55

1 Answers1

0

As far as I know, there is no way to specify the properties of the legend labels at the time of plot().

I assume you can know how many dataset you have in each dictionaries, and that you generate a legend for each one. If so, then it is easy to only modify the legends corresponding to the 2nd series of lines:

dict1 = {f'label#1 {i+1}':np.random.random(size=(5,)) for i in range(3)}
dict2 = {f'label#2 {i+1}':np.random.random(size=(5,)) for i in range(4)}

for l,d in dict1.items():
    plt.plot(d, label=l)
for l,d in dict2.items():
    plt.plot(d, label=l)

leg = plt.legend()
for text in leg.get_texts()[len(dict1):]:
    plt.setp(text, color = 'w')

enter image description here

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
  • In principle this could work if I had only two dictionaries as in my example and I wanted to modify the last one, this would work. In a more general case, I would have to do the book-keeping myself. But it could be made to work. – wander95 Jun 19 '19 at 21:20