简体   繁体   English

如何添加箱形图以分散matplotlib中的数据

[英]how to add box plot to scatter data in matplotlib

I have the following data and after plotting scatter data point, I would like to add boxplot around each set of position. 我有以下数据,在绘制散点数据点后,我想在每组位置周围添加boxplot。 Here is my code for plotting the scatter plot: 这是我绘制散点图的代码:

%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');

when i add plt.boxplot, it captures all data not individual position. 当我添加plt.boxplot时,它将捕获所有数据,而不是单个位置。 I appreciate the answers either in matplotlib or seaborn. 我对matplotlib或seaborn中的答案表示赞赏。

thanks 谢谢

A good way would be using pandas: 一个好的方法是使用熊猫:

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

output: 输出:

在此处输入图片说明

Here's a condensed solution to how to map your H array by X and plot it using matplotlib : 这是关于如何通过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)

Outcome: 结果:

在此处输入图片说明

you can add grid with plt.grid(True) 您可以使用plt.grid(True)添加网格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM