如何在循环中为重叠直方图绘制垂直平均线
How to draw vertical average lines for overlapping histograms in a loop
我正在尝试使用 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')
我还必须在图例中添加每个直方图的均值和标准差值。
我该怎么做?提前谢谢你。
我推荐你使用axes
来绘制你的图形。请查看下面的代码和美工教程 here.
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()
我正在尝试使用 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')
我还必须在图例中添加每个直方图的均值和标准差值。
我该怎么做?提前谢谢你。
我推荐你使用axes
来绘制你的图形。请查看下面的代码和美工教程 here.
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()