python - 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()
解决方案
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()
推荐阅读
- java - 如何覆盖子类中超类的属性?
- excel - 使用 VBA 将公式转换为 Excel 表格
- elasticsearch - 如何将参数放入query.script.script.params?
- javascript - 制作下拉框链接,具体取决于下拉选择 + 在下拉选择中更改 CSS
- spring-boot - 无法启动嵌入式 Tomcat 服务器 - 无效的密钥库格式
- azure - 使用 Pulumi.Azure 部署现有应用服务时出错
- node.js - 序列化子查询
- ibm-mq - 本地队列未出现在队列文件夹下
- python - 多项选择python测验:随机选择的问题,使用文本文件和列表的随机排序答案
- python-3.x - 熊猫根据所选列的重复值排列行