如何在matplotlib中添加box-plot散点数据

2024-04-27 04:02:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据,在绘制散点数据点后,我想在每个位置集周围添加框线图。下面是我绘制散点图的代码:

%matplotlib inline
import matplotlib.pyplot as plt

X = [1, 1, 1, 1, 1, 1, 1, 
      2, 2, 2, 2, 2, 2, 2, 
     3, 3, 3, 3, 3, 3, 3,
     4, 4, 4, 4, 4, 4, 4,
     5, 5, 5, 5, 5, 5, 5,
     6, 6, 6, 6, 6, 6, 6,
     7, 7, 7, 7, 7, 7, 7,
     8, 8, 8, 8, 8, 8, 8,
     9, 9, 9, 9, 9, 9, 9,
     10, 10, 10, 10, 10, 10, 10,
     11, 11, 11, 11, 11, 11, 11,
     12, 12, 12, 12, 12, 12, 12,
     13, 13, 13, 13, 13, 13, 13,
     14, 14, 14, 14, 14, 14, 14,
     15, 15, 15, 15, 15, 15, 15]

H = [15, 17, 16, 20, 15, 18, 15,
      17, 16, 16, 20, 19, 18, 15,
      20, 22, 20, 22, 19, 21, 21,
      19, 21, 20, 23, 21, 20, 22,
      21, 23, 22, 20, 24, 22, 20,
      20, 19, 20, 18, 21, 17, 19,
      18, 20, 16, 15, 17, 20, 19,
       19, 19, 18, 21, 21, 16, 19,
       21, 22, 22, 24, 24, 23, 25,
       28, 26, 30, 27, 26, 29, 30,
       27, 26, 29, 31, 27, 29, 30,
       25, 26, 27, 28, 25, 27, 30,
      31, 28, 25, 27, 30, 25, 31,
      28, 26, 30, 28, 29, 27, 31,
      24, 26, 25, 28, 26, 23, 25]

fig, axes = plt.subplots(figsize=(8,5))
axes.scatter(X, H, color='b')
axes.set_xlabel('Pos');
axes.set_ylabel('H, µm');

当我添加plt.box图,它捕获所有数据而不是单个位置。我很欣赏matplotlib或seaborn的答案。在

谢谢


Tags: 数据代码importmatplotlibasfig绘制inline
2条回答

一个很好的方法是使用熊猫:

df = pd.DataFrame({'X':X, 'H': H})
ax=df.plot(kind='scatter', x='X', y='H')
df.boxplot(by='X', ax=ax)
plt.show()

输出:

enter image description here

下面是一个简明的解决方案,如何通过X映射H数组并使用matplotlib绘制它:

groups = [[] for i in range(max(X))]
[groups[X[i]-1].append(H[i]) for i in range(len(H))]
plt.boxplot(groups)

结果:

enter image description here

您可以使用plt.grid(True)添加网格

相关问题 更多 >