Change color of individual boxes in pandas boxplot subplots
Asked Answered
S

2

10

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

Scruffy answered 21/6, 2018 at 8:34 Comment(1)
R
12

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.

Rms answered 21/6, 2018 at 11:25 Comment(4)
Thanks Thomas :) It was very helpful. Just a mention that I ended up using bp_dict.iteritems(): as I was getting the attribute error - "AttributeError: 'Series' object has no attribute 'items' "Scruffy
Hi Thomas., how to go about retaining independent axis (y and x) for each subplot? I used for i,el in enumerate(list(df.columns.values)): df.boxplot(el, by=metacategory,ax=axes.flatten()[i]) but wasn't able to apply independent colors to each box in that case...Scruffy
#50971591Scruffy
@JALO-JusAnotherLivngOrganism Thanks for the comment -- I edited the answer slightly. I'll also have a look at your other question ...Boothman
M
9

Although you name the return of df.boxplot bp, it really is a(n) (array of) axes. Inspecting the axes to get the individual parts of a boxplot is cumbersome (but possible).

First, in order to be able to colorize the interior of the boxes you need to turn the boxes to patches, df.boxplot(..., patch_artist=True).

Then you would need to find the boxes within all the artists in the axes.

# We want to make the 4th box in the second axes red    
axes[1].findobj(matplotlib.patches.Patch)[3].set_facecolor("red")

Complete code:

import pandas as pd
import numpy as np
import matplotlib
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))
axes = df.boxplot(by="models", layout=(len(df.columns)-1,1), figsize=(6,8), patch_artist=True)

for ax in axes:
    ax.set_xlabel('')

# We want to make the 4th box in the second axes red    
axes[1].findobj(matplotlib.patches.Patch)[3].set_facecolor("red")

fig = axes[0].get_figure()
fig.suptitle('New title here')
plt.show()

enter image description here

Micronucleus answered 21/6, 2018 at 11:38 Comment(5)
Thanks a lot for your input :) Your answer really helped me understand the structure better. Both of yours answers were helpful and perfect. I am accepting Thomas's answer just to respect the fact that he answered it first. I wish there was accept both option..Thanks a lot once again. Btw, I am still in learning process, any suggestions on how to independently pursue the structure of a variable/ assignment? So as to understand which indices to call for? Thanks again. Regards JALOScruffy
Oh, I did not see the other answer. It's probably the better one, because you do not have to find the objects in the axes (this is relevant if you have other plot objects in the axes as well). Not sure I understand what you mean by "independently pursue the structure of a variable/ assignment".Micronucleus
I meant how to find objects in the axes. For example, as a novice I was trying to print the axes. And I was trying to manually assign limits to the y-axis for each subplot (subplots in a row share the common y axis/ x-axis). I am using ymx=max(df.loc[row_key]); ax.set_ylim(0, ymx), but I think there is a command for keeping the axis separate? for i,el in enumerate(list(df.columns.values)[:-1]): tt.boxplot(el, by=metacategory,ax=axes.flatten()[i]) helps but then I am not able to color the individual boxes that way...findobj not there for a subplot..Scruffy
I think you are trying to compress a complete question into a 300 character comment here. I don't think I understand your problem well enough in this compressed manner.Micronucleus
Here is the question: #50971591Scruffy

© 2022 - 2024 — McMap. All rights reserved.