分组boxplots matplotlib

时间:2017-12-29 23:30:23

标签: python matplotlib

有没有办法在matplotlib中对boxplots进行分组而不使用seaborn或其他库?

e.g。在下面,我想沿x轴有块,并按条件分组绘制值(所以将有16个盒子)。就像seaborn的色调论证所完成的那样。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

blocks = 4
conditions = 4
ndatapoints = blocks * conditions

blockcol = np.repeat(list(range(1, conditions+1)), blocks)
concol = np.repeat(np.arange(1, conditions+1, 1), blocks)
trialcol = np.arange(1, ndatapoints+1, 1)
valcol = np.random.normal(0, 1, ndatapoints)

raw_data = {'blocks': np.repeat(list(range(1, conditions+1)), blocks),
           'condition': list(range(1, conditions+1))*blocks,
           'trial': np.arange(1, ndatapoints+1, 1),
           'value': np.random.normal(0, 1, ndatapoints)}

df = pd.DataFrame(raw_data)
df

    blocks  condition  trial     value
0        1          1      1  1.306146
1        1          2      2 -0.024201
2        1          3      3 -0.374561
3        1          4      4 -0.093366
4        2          1      5 -0.548427
5        2          2      6 -1.205077
6        2          3      7  0.617165
7        2          4      8 -0.239830
8        3          1      9 -0.876789
9        3          2     10  0.656436
10       3          3     11 -0.471325
11       3          4     12 -1.465787
12       4          1     13 -0.495308
13       4          2     14 -0.266914
14       4          3     15 -0.305884
15       4          4     16  0.546730

我似乎找不到任何例子。

1 个答案:

答案 0 :(得分:0)

我想你只想要一个因子图:

import numpy
import pandas
import seaborn

blocks = 3
conditions = 4
trials = 12
ndatapoints = blocks * conditions * trials

blockcol = list(range(1, blocks + 1)) * (conditions * trials)
concol =  list(range(1, conditions + 1)) * (blocks * trials)
trialcol = list(range(1, trials + 1)) * (blocks * conditions)
valcol = numpy.random.normal(0, 1, ndatapoints)

fg = pandas.DataFrame({
    'blocks': blockcol,
    'condition': concol,
    'trial': trialcol,
    'value': valcol
}).pipe(
    (seaborn.factorplot, 'data'),
    x='blocks', y='value', hue='condition',
    kind='box'
)

enter image description here