单变量Python盒形图

2024-10-01 15:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用这个python循环打印数据集中每个变量的所有boxplots。在

colNameList = list(df.columns)
for i in range (0, len(df.columns)):
    df.boxplot(column=colNameList[i])

其中df是我的数据集。在

为什么这个简单的代码只显示最后一个方框图?在


Tags: columns数据代码indfforlenrange
2条回答

如果要为每个变量单独绘制,只需将表演()在for循环中:

import matplotlib.pyplot as plt
import pandas as pd

for i in df.columns:
    df.boxplot(column=i)
    plt.show()

您可以用一种更为python的方式编写代码:测向柱已经是一个列表,并且在该列表上完成了迭代

IIUC,您需要为每个列指定一个框,这是^{}的默认值。在

示例数据帧

df = pd.DataFrame({'col1':np.random.randint(0,9,100),
                   'col2':np.random.randint(2,12,100),
                   'col3':np.random.randint(4,14,100)})

>>> df.head()
   col1  col2  col3
0     6     9     4
1     5     2     8
2     0     7    11
3     0    10     9
4     0     3     8

绘图:

^{pr2}$

enter image description here

如果只需要某些列:

df[['col1', 'col2']].boxplot()
# or
df.boxplot(column=['col1', 'col2'])

enter image description here

编辑根据您的评论,这里有一种方法可以将每个单独的框保存为单独的框线图,以便您可以单独查看它们。在

for i in df.columns:
    df.boxplot(column=i)
    plt.savefig('plot'+str(i)+'.png')
    plt.close()

相关问题 更多 >

    热门问题