5

I am plotting a series of boxplots on the same axes and want to adda legend to identify them. Very simplified, my script looks like this:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df={}
bp={}
positions = [1,2,3,4]
df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
colour=['red','blue']
fig, ax = plt.subplots()
for i in [0,1]:
    bp[i] = df[i].plot.box(ax=ax,
                          positions = positions,
                          color={'whiskers': colour[i],
                                 'caps': colour[i],
                                 'medians': colour[i],
                                 'boxes': colour[i]}
                          )
plt.legend([bp[i] for i in [0,1]], ['first plot', 'second plot'])
fig.show()

The plot is fine, but the legend is not drawn and I get this warning

    UserWarning: Legend does not support <matplotlib.axes._subplots.AxesSubplot object at 0x000000000A7830F0> instances.
A proxy artist may be used instead.

(I have had this warning before when adding a legend to a scatter plot, but the legend was still drawn, so i could ignore it. )

Here is a link to a description of proxy artists, but it is not clear how to apply this to my script. Any suggestions?

1 Answer 1

5

'pandas' plots return AxesSubplot objects which can not be used for generating legends. You must generate you own legend using proxy artist instead. I have modified your code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
df={}
bp={}
positions = [1,2,3,4]
df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
colour=['red','blue']
fig, ax = plt.subplots()
for i in [0,1]:
    bp[i] = df[i].plot.box(ax=ax,
                          positions = positions,
                          color={'whiskers': colour[i],
                                 'caps': colour[i],
                                 'medians': colour[i],
                                 'boxes': colour[i]}
                          )

red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')
plt.legend(handles=[red_patch, blue_patch])

plt.show()

The results are shown below:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.