Combining plt.plot(x,y) with plt.boxplot()
Asked Answered
P

2

20

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?

Popsicle answered 9/5, 2011 at 14:41 Comment(0)
D
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()

enter image description here

Dric answered 9/5, 2011 at 19:38 Comment(4)
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 positionsPopsicle
+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
G
0

This is what has worked for me:

  1. plot box-plot
  2. get boxt-plot x-axis tick locations
  3. 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-')


Galarza answered 23/5, 2021 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.