绘制所有列的直方图

时间:2018-12-06 07:44:15

标签: python-3.x pandas matplotlib

我有一个包含多列的数据。

Country    Weight    # of food/day  ....
---------------------------------------------
USA         180         4
China       190         12
USA         150         2
Canada      300         10

我想为每个列创建(单独的)直方图,以使histogram_1显示“国家”的分布,histogram_2显示“重量”的分布,等等。

我目前正在使用熊猫上传和处理数据。

这样做很简单吗?

for column in df:
    plt.hist(column)
    plt.show()

如果我的想法听起来很愚蠢,请原谅我。

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

可以用这个代替for循环,生成所有数值列的直方图!

df.hist(bins=10, figsize=(25, 20))

答案 1 :(得分:0)

如果要在不同的窗口中显示直方图,则可以通过以下方式进行操作:

df.set_index('Country', inplace=True)
for col in df.columns:
    df[col].plot.bar()
    plt.show()

答案 2 :(得分:0)

为非数字或离散值定义直方图并不是明确的。通常的问题是“每种独特的种类有多少种?”。这可以通过.value_counts来实现。由于您说的是“直方图数量==列数(特征)数” ,因此我们可能会为每列创建一个子图。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"Countries" : ["USA", "Mexico", "Canada", "USA", "Mexico"],
                   "Weight" : [180, 120, 100, 120, 130],
                   "Food" : [2,2,2,4,2]})

fig, axes = plt.subplots(ncols=len(df.columns), figsize=(10,5))
for col, ax in zip(df, axes):
    df[col].value_counts().sort_index().plot.bar(ax=ax, title=col)

plt.tight_layout()    
plt.show()

enter image description here