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

2 Answers2

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.

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63
  • 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' " – JALO - JusAnotherLivngOrganism Jun 21 '18 at 13:00
  • 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... – JALO - JusAnotherLivngOrganism Jun 21 '18 at 14:03
  • https://stackoverflow.com/questions/50971091/independent-axis-for-each-subplot-in-pandas-boxplot – JALO - JusAnotherLivngOrganism Jun 21 '18 at 14:36
  • @JALO-JusAnotherLivngOrganism Thanks for the comment -- I edited the answer slightly. I'll also have a look at your other question ... – Thomas Kühn Jun 25 '18 at 06:58
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

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 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 JALO – JALO - JusAnotherLivngOrganism Jun 21 '18 at 12:58
  • 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". – ImportanceOfBeingErnest Jun 21 '18 at 13:11
  • 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.. – JALO - JusAnotherLivngOrganism Jun 21 '18 at 13:59
  • 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. – ImportanceOfBeingErnest Jun 21 '18 at 14:03
  • Here is the question: https://stackoverflow.com/questions/50971091/independent-axis-for-each-subplot-in-pandas-boxplot – JALO - JusAnotherLivngOrganism Jun 21 '18 at 14:32