Fabio Lamanna
Fabio Lamanna

Reputation: 21552

pandas - boxplot median color settings issues

I'm running Pandas 0.16.2 and Matplotlib 1.4.3. I have this issue coloring the median of the boxplot generated by the following code:

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])

fig, ax = plt.subplots()

medianprops = dict(linestyle='-', linewidth=2, color='blue')

bp = df.boxplot(medianprops=medianprops)

plt.show()

That returns:

enter image description here

It appears that the color setting is not read. Changing only the settings of linestyle and linewidth the plot reacts correctly.

medianprops = dict(linestyle='-.', linewidth=5, color='blue')

enter image description here

Anyone can reproduce it?

Upvotes: 7

Views: 6399

Answers (2)

Fabio Lamanna
Fabio Lamanna

Reputation: 21552

Actually the following workaround works well, returning a dict from the boxplot command:

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])

fig, ax = plt.subplots()

bp = df.boxplot(return_type='dict')

and then assign directly colors and linewidth to the medians with:

[[item.set_color('r') for item in bp[key]['medians']] for key in bp.keys()]
[[item.set_linewidth(0.8) for item in bp[key]['medians']] for key in bp.keys()]

Upvotes: 1

Diziet Asahi
Diziet Asahi

Reputation: 40697

Looking at the code for DataFrame.boxplot() there is some special code to handle the colors of the different elements that supersedes the kws passed to matplotlib's boxplot. In theory, there seem to be a way to pass a color= argument containing a dictionary with keys being 'boxes', 'whiskers', 'medians', 'caps' but I can't seem to get it to work when calling boxplot() directly.

However, this seem to work:

df.plot(kind='box', color={'medians': 'blue'}, 
        medianprops={'linestyle': '--', 'linewidth': 5})

see Pandas Boxplot Examples

Upvotes: 8

Related Questions