【问题标题】:Python (matplotlib): Arrange multiple subplots (histograms) in grid [duplicate]Python(matplotlib):在网格中排列多个子图(直方图)[重复]
【发布时间】:2021-10-11 01:40:50
【问题描述】:

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

我能够创建图表,但困难在于将它们排列在网格中。我使用网格函数来实现这一点,但我需要在各个位置将图表链接到它。

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

你们能帮帮我吗?

【问题讨论】:

    标签: python matplotlib graph histogram


    【解决方案1】:

    您还继续使用 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()
    

    【讨论】:

      【解决方案2】:

      你可以使用 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")
      

      等等。

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 2014-02-03
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        • 2012-09-04
        • 2019-02-05
        • 2015-06-14
        • 1970-01-01
        相关资源
        最近更新 更多