Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to view histograms juxtaposed using matplotlib

I am trying to visualize how the distributions differ based on the flag column:

Sample Data:

np.random.seed(0)
df = pd.DataFrame({'col1' : np.random.uniform(size = 100),
                  'col2' : np.random.uniform(size = 100),
                  'col3' : np.random.uniform(size = 100),
                  'flag' : np.random.choice([0,1], 100)})
df
    col1        col2        col3        flag
0   0.548814    0.677817    0.311796    0
1   0.715189    0.270008    0.696343    0
2   0.602763    0.735194    0.377752    1
3   0.544883    0.962189    0.179604    1
4   0.423655    0.248753    0.024679    1
... ... ... ... ...
95  0.183191    0.490459    0.224317    0
96  0.586513    0.227415    0.097844    0
97  0.020108    0.254356    0.862192    0
98  0.828940    0.058029    0.972919    1
99  0.004695    0.434417    0.960835    0

I can view the histograms using 2 for loops one each for flag == 0 and flag == 1 using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for col in df.loc[df['flag'] == 0, ['col1', 'col2', 'col3']].columns:
    plt.hist(df[col])
    plt.title(col)
    plt.show()

Could someone please let me know if I can generate visualizations wherein the histograms for each column is placed side by side, one each for different flag columns.

>Solution :

is well suited for this:

import seaborn as sns
...
sns.displot(df.melt(id_vars='flag'), row='variable', col='flag', x='value')

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading