将plt.plot(x,y)与plt.boxplot()相结合

时间:2011-05-09 14:41:30

标签: python numpy matplotlib plot boxplot

我正在尝试将一个普通的matplotlib.pyplot plt.plot(x,y)与变量y结合起来作为变量x的函数和一个箱线图。但是,我只想要x的某些(可变)位置上的箱线图,但这在matplotlib中似乎不起作用?

2 个答案:

答案 0 :(得分:20)

你想要这样的东西吗? positions kwarg boxplot允许您将箱形图放置在任意位置。

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

答案 1 :(得分:0)

这对我有用:

  1. 绘制箱线图
  2. 获取 boxt-plot x 轴刻度位置
  3. 使用箱线图 x 轴刻度位置作为线图的 x 轴值
# 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-')