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?
Asked
Active
Viewed 2.1k times
19

Serenity
- 35,289
- 20
- 120
- 115

ruben baetens
- 2,806
- 6
- 25
- 31
2 Answers
29
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()

Joe Kington
- 275,208
- 71
- 604
- 463
-
Yes, thank you, this is exactly what i wanted. Iwas always trying to do something like plt.plot([x,y]) in boxplot, but failed ... seemsi misunderstand the kwarg `positions` – ruben baetens May 10 '11 at 07:22
-
+1 for showing how to conserve the xtick locations. When working with axes the commands are `locs = ax.get_xticks()` and `ax.set_xticks(locs)` – MrCyclophil Mar 05 '16 at 20:01
-
Additionally to my comment above one actually needs to add `ax.set_xticklabels(locs)` as well to get the labels right. – MrCyclophil Mar 06 '16 at 18:48
-
Great answer without the need to use seaborn! Great! – seralouk May 07 '22 at 13:36
0
This is what has worked for me:
- plot box-plot
- get boxt-plot x-axis tick locations
- use box-plot x-axis tick locations as x-axis values for the line plot
# Plot Box-plot
ax.boxplot(data, positions=x, notch=True)
# Get box-plot x-tick locations
locs=ax.get_xticks()
# Plot a line between the means of each dataset
# x-values = box-plot x-tick locations
# y-values = means
ax.plot(locs, y, 'b-')

jumbofiatco
- 21
- 5