Search code examples
pythondataframeplothistogram

How to plot these histograms next to each other


I want to take a look onto data distribution. Problem is I want to make loop that displays each dataframe column separately. With this approach every column's histogram is plotted on one graphical area.

for x in df.columns.to_list():
  df[x].hist(bins=120)

histogram_image

How to divide these histograms to separated images?


Solution

  • Having sample data with 3 columns:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    d = {'col1': [1, 2, 3, 4, 5, 6, 3, 5], 
         'col2': [1, 2, 2, 2, 5, 6, 3, 5], 
         'col3': [1, 2, 2, 2, 2, 2, 2, 6], }
    df = pd.DataFrame(data=d)
    
    df
    

    enter image description here

    You can use subplots from matplotlib to see each column on separate histogram:

    fig, axs = plt.subplots(len(df.columns), figsize=(8,12))
    i=0
    
    for x in df.columns.to_list():
        axs[i].hist(df[x], bins=10)
        i=i+1
    

    enter image description here