How to change the linestyle of whiskers in pandas boxplots?

16.4k views Asked by At

Is there a way to change the linestyle of the whiskers in pandas boxplots to '-'? Default seems to be '--'.

I have tried:

color = dict(boxes='black', whiskers='black', medians='red', caps='black')
styles=dict(whiskers='-')
bp = df.plot.box(color=color, style=styles)

However, while the colors turn out the way I want, the style input does not seem to affect the plot at all.

Here is an example. I always get dashed lines for my whiskers, but would like solid lines.

I have also tried

boxprops = dict(linewidth=1.0, color='black')
whiskerprops = dict(linestyle='-',linewidth=1.0, color='black')
plt.figure()
df.boxplot(boxprops=boxprops, whiskerprops=whiskerprops)

Here, df.boxplot does not take the inputs at all.

This is closely related to Pandas boxplot: set color and properties for box, median, mean

3

There are 3 answers

0
knut_h On BEST ANSWER

Ted Petrou's commments helped:

Put the whiskerprops = dict() directly in to the df.plot.box line:

color = dict(boxes='black', whiskers='black', medians='red', caps='black')
bp = df.plot.box(color=color,whiskerprops = dict(linestyle='-',linewidth=1.0
, color='black'))

As for df.boxplot(), there seems to be a problem with byarguments. Including whiskerprops and boxprops directly into the argument, here, helped as well. However I could still not change the boxes' color! It remains to be the default blue. The following code yields solid-line, black whiskers, however the boxes are blue. Linewidth of boxes can be changed tho!

plt.figure()
df.boxplot(boxprops= dict(linewidth=1.0, color='black')
, whiskerprops=dict(linestyle='-',linewidth=1.0, color='black'))

If anyone can help with changing boxes colors in df.boxplot(), please do comment. From the pandas documentation I get, that people should rather use df.plot.box anyways tho.

1
wwii On

I don't have pandas here but it uses matplotlib. pyplot.boxplot returns

A dictionary mapping each component of the boxplot to a list of the matplotlib.lines.Line2D instances created.

One set of lines is for the whiskers. You can set the linestyle property for each whisker by accessing it through the dictionary.

from pprint import pprint
import matplotlib.pyplot as plt

data = [[1, 2, 3, 4, 5], [2, 3, 4], [1, 1.2, 1.4, 1.8]]
a = plt.boxplot(data)
pprint(a)
for whisker in a['whiskers']:
    whisker.set_linestyle('-.')
    print(whisker.get_linestyle())
plt.show()
plt.close()

Available linestyles are shown in this line_styles_reference example.

0
Michael James Kali Galarnyk On
import numpy as np
import pandas as pd

mu, sigma = 0, 1 
s = np.random.normal(mu, sigma, 1000)

df = pd.DataFrame(s)

bPlot = df.boxplot(whiskerprops = dict(linestyle='--'
                           , linewidth=2))

enter image description here