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?
Combining plt.plot(x,y) with plt.boxplot()
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()
+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)
–
Czarism Additionally to my comment above one actually needs to add
ax.set_xticklabels(locs)
as well to get the labels right. –
Czarism Great answer without the need to use seaborn! Great! –
Borglum
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-')
© 2022 - 2024 — McMap. All rights reserved.
positions
– Popsicle