Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay box plots on bars matplotlib/python

I am trying to overlay a set of box plots on bars using separate y axis in matplotlib. I can't find an example anywhere and have tried everything I can think of with ax.set_zorder() and ax2.set_alpha(). Is there a way to set the background opaque from just the box plots? ax.patch.set_facecolor('None') removes the background completely...

Here's what I've tried:

import matplotlib.pyplot as plt
import numpy as np

example_data = [1,2,1],[1,2,2,2],[3,2,1]

data = [i for i in example_data]

data_len = [len(i) for i in example_data]

labels = ['one','two','three']

plt.figure()

fig, ax = plt.subplots()

plt.boxplot(data)

ax.set_xticklabels(labels,rotation='vertical')


ax2 = ax.twinx()

ax2.bar(ax.get_xticks(),data_len,color='yellow', align='center')

ax2.set_zorder(1)

ax.set_zorder(2)

ax2.set_alpha(0.1)

ax.patch.set_facecolor('None')

plt.show()

Thanks in advance for your help.

like image 700
Liam McIntyre Avatar asked Nov 28 '16 04:11

Liam McIntyre


1 Answers

How about just changing the order of your plots so that the box plot is displayed after the bar plot? For example:

import matplotlib.pyplot as plt
import numpy as np

example_data = [[1,2,1], [1,2,2,2], [3,2,1]]
data_len = [len(i) for i in example_data]
labels = ['one','two','three']

fig, ax = plt.subplots()
ax.bar(range(1, len(data_len)+1), data_len, color='yellow', align='center')
ax2 = ax.twinx()
ax2.boxplot(example_data)
ax2.set_ylim(ax.get_ylim())
ax.set_xticklabels(labels, rotation='vertical')
plt.show()

This would give you:

bar and box plot

like image 111
Martin Evans Avatar answered Oct 17 '22 13:10

Martin Evans