2016-06-30 110 views
3

我的數據幀(熊貓的結構)看起來像上面 enter image description here大熊貓箱線圖了多列

現在我想讓箱圖放到不同的畫布上每個功能。分離條件是第一欄。我有類似的直方圖陰謀(下面的代碼),但我不能爲boxplot製作工作版本。

hist_params = {'normed': True, 'bins': 60, 'alpha': 0.4} 
# create the figure 
fig = plt.figure(figsize=(16, 25)) 
for n, feature in enumerate(features): 
    # add sub plot on our figure 
    ax = fig.add_subplot(features.shape[1] // 5 + 1, 6, n + 1) 
    # define range for histograms by cutting 1% of data from both ends 
    min_value, max_value = numpy.percentile(data[feature], [1, 99]) 
    ax.hist(data.ix[data.is_true_seed.values == 0, feature].values, range=(min_value, max_value), 
      label='ghost', **hist_params) 
    ax.hist(data.ix[data.is_true_seed.values == 1, feature].values, range=(min_value, max_value), 
      label='true', **hist_params) 
    ax.legend(loc='best') 

    ax.set_title(feature) 

以上代碼產生這樣的輸出爲(僅連接它的一部分): enter image description here

回答

5

DataFrame.boxplot()自動執行此相當好:

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

df = pd.DataFrame({'is_true_seed': np.random.choice([True, False], 10), 
        'col1': np.random.normal(size=10), 
        'col2': np.random.normal(size=10), 
        'col3': np.random.normal(size=10)}) 

fig, ax = plt.subplots(figsize=(10, 10)) 
df.boxplot(['col1', 'col2', 'col3'], 'is_true_seed', ax) 

的第一個參數告訴大熊貓列繪製哪個,第二列(由你稱之爲分離條件)組成的列,以及繪製軸的第三列。

列出所有列,但您想分組的列可能會很乏味,但您可以通過省略第一個參數來避免它。您必須明確指出另外兩個:

df.boxplot(by='is_true_seed', ax=ax)