首页 > 解决方案 > Pandas - 在 Dataframe 子图中重复 vline

问题描述

我有 2x3 子图显示来自 Pandas 数据框的直方图。我想在每个直方图上添加一条 vline。您可以看到只有最后一个子图显示垂直线,这就是错误...

第二个问题:我错过了子图第一行的 x_labels?

有什么想法可以解决这个问题吗?最好的问候, 同行

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns

params = {"axes.titlesize": "10", "xtick.labelsize": "8", "ytick.labelsize": "8"}
matplotlib.rcParams.update(params)

mu, sigma = 0, 0.1  # mean and standard deviation
nse = np.random.normal(mu, sigma, 1000)

df = pd.DataFrame(
    {
        "Stringer 1": nse,
        "Stringer 3": nse * 2,
        "Stringer 5": nse * 4,
        "Stringer 7": nse,
        "Stringer 8": nse * 6,
    }
)


# Layout für Diagramme
fig, ax = plt.subplots(2, 3, sharex="col", sharey="row")


m = 0
for i in range(2):
    for j in range(3):
        h = df.hist(column=df.columns[m], bins=50, ax=ax[i, j], grid=False)
        plt.axvline(1, color="yellow")
        m += 1

fig.set_facecolor("w")

plt.tight_layout()
plt.show()

在此处输入图像描述

标签: pythonpandasdataframematplotlib

解决方案


plt.subplots给你一个数字和一个数组ax。然后,您可以使用zip.

# Removing `sharex` puts the x labels on each row
fig, axes = plt.subplots(2, 3, sharey="row")

for col, ax in zip(df.columns, axes.flatten()):
    # Set title
    ax.set_title(col)
    # Plot histogram
    ax.hist(df[col], bins=50)
    # Add vline
    ax.axvline(1, color="y")
    # Adjust spacing
    plt.subplots_adjust(wspace=.5, hspace=.5)

plt.tight_layout()
plt.show()

直方图网格


推荐阅读