python-3.x - 如何在循环中为重叠直方图绘制垂直平均线
问题描述
我正在尝试使用 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
用来绘制你的图。请参阅下面的代码和此处的艺术家教程。
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()
推荐阅读
- prolog - Prolog - 到两点的距离
- php - 完整图像而不是缩略图
- flutter - 选项卡上的路线导致黑屏
- android - 聊天recyclerview的type2不显示
- python - 创建分发时 setuptools 不包括烧瓶模板
- python - Windows 10 RTX 2070 使用带有 anaconda 优化的 keras gpu?
- ubuntu - 在 Ubuntu 18.04 上安装 nautilus 失败。(未满足的依赖项)
- c# - 为什么 python 中的相对路径在从 C# 运行时不起作用,但在 c# 之外使用相同的解释器时起作用?
- linux - 使用带有 git 钩子的脚本时找不到文件或目录
- javascript - 如何根据异步函数的返回结果使用 sweetalert 创建不同的按钮列表?