将plt.plot(x,y)与plt.boxplot()结合
我想把普通的 matplotlib.pyplot 的 plt.plot(x,y)
和变量 y
作为变量 x
的函数结合起来,同时还想加一个箱线图。不过,我只想在 x
的某些特定位置显示箱线图,但在 matplotlib 中似乎无法做到这一点?
2 个回答
0
这是我用过的有效方法:
- 画一个箱线图
- 获取箱线图上x轴刻度的位置
- 把箱线图的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-')
29
你想要的效果是这样的吧?在 boxplot
函数中,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()