Combining plt.plot(x,y) with plt.boxplot()

ruben baetens picture ruben baetens · May 9, 2011 · Viewed 12.8k times · Source

I'm trying to combine a normal matplotlib.pyplot plt.plot(x,y) with variable y as a function of variable x with a boxplot. However, I only want a boxplot on certain (variable) locations of x but this does not seem to work in matplotlib?

Answer

Joe Kington picture Joe Kington · May 9, 2011

Are you wanting something like this? The positions kwarg to boxplot allows you to place the boxplots at arbitrary positions.

import matplotlib.pyplot as plt
import numpy as np

# Generate some data...
data = np.random.random((100, 5))
y = data.mean(axis=0)
x = np.random.random(y.size) * 10
x -= x.min()
x.sort()

# Plot a line between the means of each dataset
plt.plot(x, y, 'b-')

# Save the default tick positions, so we can reset them...
locs, labels = plt.xticks() 

plt.boxplot(data, positions=x, notch=True)

# Reset the xtick locations.
plt.xticks(locs)
plt.show()

enter image description here