分别绘制所有 Pandas 数据框列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55567706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:22:20  来源:igfitidea点击:

Plot all pandas dataframe columns separately

pythonpandasmatplotlibsubplot

提问by Manu Sharma

I have a pandas dataframe who just has numeric columns, and I am trying to create a separate histogram for all the features

我有一个只有数字列的 Pandas 数据框,我正在尝试为所有特征创建一个单独的直方图

ind group people value value_50
 1      1    5    100    1
 1      2    2    90     1
 2      1    10   80     1
 2      2    20   40     0
 3      1    7    10     0
 3      2    23   30     0

but in my real life data there are 50+ columns, how can I create a separate plot for all of them

但在我的现实生活数据中有 50 多列,我如何为所有这些列创建一个单独的图

I have tried

我试过了

df.plot.hist( subplots = True, grid = True)

It gave me an overlapping unclear plot.

它给了我一个重叠的不清楚的情节。

how can I arrange them using pandas subplots = True. Below example can help me to get graphs in (2,2) grid for four columns. But its a long method for all 50 columns

我如何使用 pandas subplots = True 来安排它们。下面的示例可以帮助我在 (2,2) 网格中获取四列的图形。但对于所有 50 列来说,这是一个很长的方法

fig, [(ax1,ax2),(ax3,ax4)]  = plt.subplots(2,2, figsize = (20,10))

回答by ImportanceOfBeingErnest

Pandas subplots=Truewill arange the axes in a single column.

Pandassubplots=True会将轴排列在单列中。

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

df = pd.DataFrame(np.random.rand(7,20))

df.plot(subplots=True)

plt.tight_layout()
plt.show()

enter image description here

在此处输入图片说明

Here, tight_layoutisn't applied, because the figure is too small to arange the axes nicely. One can use a bigger figure (figsize=(...)) though.

此处tight_layout未应用,因为图太小而无法很好地排列轴。不过,可以使用更大的数字 ( figsize=(...))。

In order to have the axes on a grid, one can use the layoutparameter, e.g.

为了将轴放在网格上,可以使用layout参数,例如

df.plot(subplots=True, layout=(4,5))

enter image description here

在此处输入图片说明

The same can be achieved if creating the axes via plt.subplots()

如果通过以下方式创建轴,也可以实现相同的目的 plt.subplots()

fig, axes = plt.subplots(nrows=4, ncols=5)
df.plot(subplots=True, ax=axes)

回答by annhak

If you want to plot them separately (which is why I ended up here), you can use

如果你想分别绘制它们(这就是我在这里结束的原因),你可以使用

for i in df.columns:
    plt.figure()
    plt.hist(df[i])

回答by Ramon

An alternative for this task can be using the "hist" method with hyperparameter "layout". Example using part of the code provided by @ImportanceOfBeingErnest:

此任务的替代方法是使用具有超参数“布局”的“hist”方法。使用@ImportanceOfBeingErnest 提供的部分代码的示例:

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

df = pd.DataFrame(np.random.rand(7,20))

df.hist(layout=(5,4), figsize=(15,10))

plt.show()