如何为Pandas Dataframe中的每一列创建Box Plot? [英] How do I create a Box plot for each column in a Pandas Dataframe?

查看:44
本文介绍了如何为Pandas Dataframe中的每一列创建Box Plot?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框( pandas 的结构)如下所示

现在我想在单独的画布上为每个功能制作盒图。分离条件为第一柱。我有类似的直方图(代码如下),但我不能使工作版本的框图。

 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)
上面的代码产生如下输出(只附加了部分输出):

推荐答案

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)})

   is_true_seed      col1      col2      col3
0         False -0.990041 -0.561413 -0.512582
1         False  0.825099  0.827453 -0.366211
2          True  0.083442 -1.199540  0.345792
3          True  0.065715  1.560029 -0.324501
4          True -1.699770 -0.270820 -1.380125

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

第一个参数告诉 pandas 绘制哪些列,第二个参数告诉 pandas 按哪个列分组(您称之为分离条件),第三个参数告诉 pandas 在哪个轴上绘制。

列出除要分组的列以外的所有列可能会很繁琐,但可以通过省略第一个参数来避免。然后,您必须显式命名其他两个:

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

这篇关于如何为Pandas Dataframe中的每一列创建Box Plot?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆