Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Change color of individual boxes in pandas boxplot subplots

This is in reference to the following question, wherein options for adjusting title and layout of subplots are discussed: modify pandas boxplot output

My requirement is to change the colors of individual boxes in each subplot (as depicted below):

Something like this

Following is the code available at the shared link for adjusting the title and axis properties of subplots:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4',     'model5', 'model6', 'model7'], 20))
bp = df.boxplot(by="models",layout=(4,1),figsize=(6,8))
[ax_tmp.set_xlabel('') for ax_tmp in np.asarray(bp).reshape(-1)]
fig = np.asarray(bp).reshape(-1)[0].get_figure()
fig.suptitle('New title here')
plt.show()

I tried using the: ax.set_facecolor('color') property, but not successful in obtaining the desired result.

I tried accessing bp['boxes'] as well but apparently it is not available. I need some understanding of the structure of data stored in bp for accessing the individual boxes in the subplot.

Looking forward

P.S: I am aware of seaborn. But need to understand and implement using df.boxplot currently. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To adjust the colours of your boxes in pandas.boxplot, you have to adjust your code slightly. First of all, you have to tell boxplot to actually fill the boxes with a colour. You do this by specifying patch_artist = True, as is documented here. However, it appears that you cannot specify a colour (default is blue) -- please anybody correct me if I'm wrong. This means you have to change the colour afterwards. Luckily pandas.boxplot offers an easy option to get the artists in the boxplot as return value by specifying return_type = 'both' see here for an explanation. What you get is a pandas.Series with keys according to your DataFrame columns and values that are tuples containing the Axes instances on which the boxplots are drawn and the actual elements of the boxplots in a dictionary. I think the code is pretty self-explanatory:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])

df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4',     'model5', 'model6', 'model7'], 20))

bp_dict = df.boxplot(
    by="models",layout=(4,1),figsize=(6,8),
    return_type='both',
    patch_artist = True,
)

colors = ['b', 'y', 'm', 'c', 'g', 'b', 'r', 'k', ]
for row_key, (ax,row) in bp_dict.iteritems():
    ax.set_xlabel('')
    for i,box in enumerate(row['boxes']):
        box.set_facecolor(colors[i])

plt.show()

The resulting plot looks like this:

result of the above code

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...