[FIXED] How to create multiple density plot using sns.distplot for list of columns from a dataframe? "Python"

Issue

columns = list(data_no_mv)
for i in columns:
    sns.distplot(data_no_mv[i][len(columns)+1],axlabel=(i))
    plt.show()
  • data_no_mv is the data set with no missing values and has 14 columns.
  • need to plot 14 different density graphs of all the columns using distplot and loop

Solution

@Himanshu - You need to use melt() to change the data to long form and then you can plot it. In below code, I have used a random dataframe of 100x14 with column names A-N, which you can replace with your data. Note that, as you mentioned distplot, I have used it at a figure level. You can use kdeplot along with fact_grid otherwise. Also, I have set kde=True. If you are looking for bars (histogram), remove that and you will get the histogram form.

random_data = np.random.randint(1,100,size=(100,14))
df = pd.DataFrame(random_data, columns=list('ABCDEFGHIJKLMN'))

# Use melt to change data to long format 
df = df.melt(var_name='cols',  value_name='vals')

sns.displot(kind='kde', data=df, col='cols', col_wrap=4, x='vals', hue="cols", facet_kws={'sharey': False, 'sharex': False})

enter image description here



Answered By - Redox
Answer Checked By - Cary Denson (Python.Easybugfix Admin)

Related Posts

Post a Comment