Как создать подграфики для гистограмм в Pandas: несколько методов с примерами кода

Чтобы добавить подграфики для гистограмм в pandas, вы можете использовать различные методы в зависимости от ваших требований. Вот несколько методов с примерами кода:

Метод 1: использование pyplot.subplots() из Matplotlib

import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [2, 4, 6, 8, 10],
        'C': [3, 6, 9, 12, 15]}
df = pd.DataFrame(data)
# Create subplots with 2 rows and 2 columns
fig, axes = plt.subplots(nrows=2, ncols=2)
# Plot histograms on each subplot
df['A'].plot.hist(ax=axes[0, 0])
df['B'].plot.hist(ax=axes[0, 1])
df['C'].plot.hist(ax=axes[1, :])
# Add titles to subplots
axes[0, 0].set_title('Histogram of A')
axes[0, 1].set_title('Histogram of B')
axes[1, 0].set_title('Histogram of C')
# Adjust spacing between subplots
plt.tight_layout()
# Display the plot
plt.show()

Метод 2: использование метода pandas.DataFrame.hist()

import pandas as pd
# Create a DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [2, 4, 6, 8, 10],
        'C': [3, 6, 9, 12, 15]}
df = pd.DataFrame(data)
# Create subplots using DataFrame.hist() method
axarr = df.hist(layout=(2, 2))
# Set titles for subplots
for i in range(2):
    for j in range(2):
        axarr[i, j].set_title('Histogram of ' + df.columns[i * 2 + j])
# Display the plot
plt.show()

Метод 3. Использование библиотеки seaborn

import pandas as pd
import seaborn as sns
# Create a DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [2, 4, 6, 8, 10],
        'C': [3, 6, 9, 12, 15]}
df = pd.DataFrame(data)
# Create subplots using seaborn
fig, axes = plt.subplots(nrows=2, ncols=2)
# Plot histograms on each subplot
sns.histplot(df['A'], ax=axes[0, 0])
sns.histplot(df['B'], ax=axes[0, 1])
sns.histplot(df['C'], ax=axes[1, 0])
# Add titles to subplots
axes[0, 0].set_title('Histogram of A')
axes[0, 1].set_title('Histogram of B')
axes[1, 0].set_title('Histogram of C')
# Adjust spacing between subplots
plt.tight_layout()
# Display the plot
plt.show()