0

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?

reCaptcha
  • 39
  • 6

2 Answers2

0

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.

warped
  • 8,947
  • 3
  • 22
  • 49
0

You also continue use GridSpec. Visit https://matplotlib.org/stable/tutorials/intermediate/gridspec.html

for example -

    fig2 = plt.figure(constrained_layout=True)
    spec2 = gridspec.GridSpec(ncols=2, nrows=3, figure=fig2)
    f2_ax1 = fig2.add_subplot(spec2[0, 0])
    f2_ax2 = fig2.add_subplot(spec2[0, 1])
    f2_ax3 = fig2.add_subplot(spec2[1, 0])
    f2_ax4 = fig2.add_subplot(spec2[1, 1])
    f2_ax5 = fig2.add_subplot(spec2[2, 1])
    
    
    # Plot 1
    
    f2_ax1.hist(df['O'])
    f2_ax1.set_title("Openness to experience")
    f2_ax1.set_xlabel("Value")
    f2_ax1.set_ylabel("Frequency")

`   plt.show()