首页 > 解决方案 > 如何在循环中为重叠直方图绘制垂直平均线

问题描述

我正在尝试使用 matplotlib 为每个重叠的直方图绘制两条平均垂直线,并使用循环。第一张画好了,第二张不知道怎么画。我正在使用数据集中的两个变量来绘制直方图。一个变量(feat)是分类变量(0 - 1),另一个变量(objective)是数值变量。代码如下:

for chas in df[feat].unique():
   plt.hist(df.loc[df[feat] == chas, objective], bins = 15, alpha = 0.5, density = True, label = chas)
   plt.axvline(df[objective].mean(), linestyle = 'dashed', linewidth = 2)
   plt.title(objective)
   plt.legend(loc = 'upper right')

我还必须在图例中添加每个直方图的平均值和标准偏差值。

我该怎么做?先感谢您。

标签: python-3.xmatplotlibhistogram

解决方案


我建议你axes用来绘制你的图。请参阅下面的代码和此处的艺术家教程。

import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)

mu1, sigma1 = 100, 8
mu2, sigma2 = 150, 15

x1 = mu1 + sigma1 * np.random.randn(10000)
x2 = mu2 + sigma2 * np.random.randn(10000)


fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
# the histogram of the data
lbs = ['a', 'b']
colors = ['r', 'g']
for i, x in enumerate([x1, x2]):
    n, bins, patches = ax.hist(x, 50, density=True, facecolor=colors[i], alpha=0.75, label=lbs[i])
    ax.axvline(bins.mean())
ax.legend()

在此处输入图像描述


推荐阅读