Python (matplotlib): 在网格中排列多个子图(直方图)

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

我想在一个网格中排列 5 个直方图。这是我的代码和结果:

我能够创建图表,但困难在于将它们排列在网格中。我使用网格函数来实现这一点,但我需要 link 在相应的位置将图表添加到它。

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

你们能帮帮我吗?

您可以使用 plt.subplots:

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

这将创建一个 2x2 网格。您可以通过索引 hte 轴对象来访问各个位置:

左上角:

ax = axes[0,0]

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

等等。

您还继续使用 GridSpec。访问 https://matplotlib.org/stable/tutorials/intermediate/gridspec.html

例如-

    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()