Search code examples
pythonmatplotlibgraphhistogram

Python (matplotlib): Arrange multiple subplots (histograms) in grid


I want to arrange 5 histograms in a grid. Here is my code and the result:

I was able to create the graphs but the difficulty comes by arranging them in a grid. I used the grid function to achieve that but i need to link the graphs to it in the respective places.

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

Openness = df['O']
Conscientiousness = df['C']
Extraversion = df['E']
Areeableness = df['A']
Neurocitism = df['N']

grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)

# Plot 1
import matplotlib.pyplot as plt
import numpy as np
plt.hist(df['O'], bins = 100)
plt.title("Openness to experience")
plt.xlabel("Value")
plt.ylabel("Frequency")

# Plot 2
import matplotlib.pyplot as plt
import numpy as np
plt.hist(df['C'], bins = 100)
plt.title("Conscientiousness")
plt.xlabel("Value")
plt.ylabel("Frequency")

# Plot 3
import matplotlib.pyplot as plt
import numpy as np
plt.hist(df['E'], bins = 100)
plt.title("Extraversion")
plt.xlabel("Value")
plt.ylabel("Frequency")

# Plot 4
import matplotlib.pyplot as plt
import numpy as np
plt.hist(df['A'], bins = 100)
plt.title("Areeableness")
plt.xlabel("Value")
plt.ylabel("Frequency")

# Plot 5
import matplotlib.pyplot as plt
import numpy as np
plt.hist(df['N'], bins = 100)
plt.title("Neurocitism")
plt.xlabel("Value")
plt.ylabel("Frequency")

Results merge everything into one chart

But it should look like this

Could you guys please help me out?


Solution

  • You can use plt.subplots:

    fig, axes = plt.subplots(nrows=2, ncols=2)
    

    this creates a 2x2 grid. You can access individual positions by indexing hte axes object:

    top left:

    ax = axes[0,0]
    
    ax.hist(df['C'], bins = 100)
    ax.set_title("Conscientiousness")
    ax.set_xlabel("Value")
    ax.set_ylabel("Frequency")
    

    and so on.