How to connect boxplot median values

Viewed 6027

It seems like plotting a line connecting the mean values of box plots would be a simple thing to do, but I couldn't figure out how to do this plot in pandas.

I'm using this syntax to do the boxplot so that it automatically generate the box plot for Y vs. X device without having to do external manipulation of the data frame:

df.boxplot(column='Y_Data', by="Category", showfliers=True, showmeans=True)

enter image description here

One way I thought of doing is to just do a line plot by getting the mean values from the boxplot, but I'm not sure how to extract that information from the plot.

2 Answers

You can get the value of the medians by using the .get_data() property of the matplotlib.lines.Line2D objects that draw them, without having to use seaborn.

Let bp be your boxplot created as bp=plt.boxplot(data). Then, bp is a dict containing the medians key, among others. That key contains a list of matplotlib.lines.Line2D, from which you can extract the (x,y) position as follows:

bp=plt.boxplot(data)
X=[]
Y=[]
for m in bp['medians']:
    [[x0, x1],[y0,y1]] = m.get_data()
    X.append(np.mean((x0,x1)))
    Y.append(np.mean((y0,y1)))
plt.plot(X,Y,c='C1')

For an arbitrary dataset (data), this script generates this figure. Hope it helps!

Related