5

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.

Monasha
  • 711
  • 2
  • 16
  • 27
Liam McIntyre
  • 71
  • 1
  • 4

1 Answers1

6

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

Martin Evans
  • 45,791
  • 17
  • 81
  • 97