Distribution probabilities for each column data frame, in one plot

↘锁芯ラ 提交于 2019-12-06 08:08:29

I think you need to use melt to reshape your dataframe to long format, see this MVCE:

df = pd.DataFrame(np.random.random((100,5)), columns = list('ABCDE'))
dfm = df.melt(var_name='columns')
g = sns.FacetGrid(dfm, col='columns')
g = (g.map(sns.distplot, 'value'))

Output:

You're getting this wrong on two levels.

  • Python syntax.
    FacetGrid(df, col = 'A','B','C','D','E') is invalid, because col gets set to A and the remaining characters are interpreted as further arguments. But since they are not named, this is invalid python syntax.

  • Seaborn concepts.

    • Seaborn expects a single column name as input for the col or row argument. This means that the dataframe needs to be in a format that has one column which determines to which column or row the respective datum belongs.

    • You do not call the function to be used by map. The idea is of course that map itself calls it.

Solutions:

  • Loop over columns:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    df = pd.DataFrame(np.random.randn(14,5), columns=list("ABCDE"))
    
    fig, axes = plt.subplots(ncols=5)
    for ax, col in zip(axes, df.columns):
        sns.distplot(df[col], ax=ax)
    
    plt.show()
    
  • Melt dataframe

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    df = pd.DataFrame(np.random.randn(14,5), columns=list("ABCDE"))
    
    g = sns.FacetGrid(df.melt(), col="variable")
    g.map(sns.distplot, "value")
    
    plt.show()
    

I think the easiest approach is to just loop the columns and create a plot.

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

df = pd.DataFrame(np.random.random((100,5)), columns = list('ABCDE'))
for col in df.columns:
    hist = df[col].hist(bins=10)
    print("Plotting for column {}".format(col))
    plt.show()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!