【问题标题】:Plot sequential box plots in matplotlib (control and treatment groups)在 matplotlib 中绘制顺序箱线图(对照组和治疗组)
【发布时间】:2020-08-21 09:02:04
【问题描述】:

我有连续时间来自对照组和治疗组的测量值,我想绘制每次测量值的箱线图,并沿 x 轴按时间顺序排列。

我该怎么做?看起来有多个箱形图并排的例子,但是让它们根据某个时间变量组织起来让我望而却步。

我将在“整洁”的数据框中给出一些示例数据。 X是度量,T是时间,G是组。

X | T | G
==========
1 | 1 | 0
2 | 1 | 1
3 | 1 | 0
2 | 1 | 1
3 | 2 | 0
7 | 2 | 1
6 | 2 | 0
3 | 2 | 1
9 | 3 | 0
5 | 3 | 1
1 | 3 | 0
1 | 3 | 1

此示例将在时间 1、时间 2 和时间 3 有两个彼此相邻的箱线图。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(2020)
df = pd.DataFrame({
     "X": [1,2,3,2,3,7,6,3,9,5,1,1],
     "T": [1,1,1,1,2,2,2,2,3,3,3,3],    
     "G": [0,1,0,1,0,1,0,1,0,1,0,1]
})
for i in range(1,4):
    for j in range(0,2):
        plt.boxplot(df["X"][(df["T"] == i) & (df["G"] == j)])
plt.show()

这种堆叠不是我想要的。我正在寻找类似以下的内容。

【问题讨论】:

  • 到目前为止,您尝试了哪些方法来解决您的问题?另外,请确保在每个问题中包含最少的可重现代码。
  • @Arsik36 已添加!

标签: python matplotlib plot


【解决方案1】:

您可以做的是利用 by = 'column name' 参数来指定您希望按哪一列对数据进行分组。此外,传递 column = [column_1, column_2] 参数允许您指定您希望针对您的“T”变量评估哪些列。下面的代码为每列(X 和 G)创建 2 个箱线图可视化。在这两种情况下,您的数据都会按所需的“T”列分组。

# Create boxplots for columns X and G, each grouped by column T
df.boxplot(column = ['X', 'G'], # specify columns you wish to analyze
           by = 'T',            # specify column by which you wish to group data
           vert = False,        # specify whethere you want vertical or horizontal output
           figsize = (16, 8))   # specify the size of your output

# Show the result
plt.show()

以上代码的输出如下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多