python - 如何在 Python for 循环中绘制一个月的平均线?
问题描述
我有看起来像这样的代码:
for _, d in Country_sim_count.set_index('Week').groupby('Home_Country'):
fig, ax = plt.subplots()
d['SIM_total'].plot()
plt.axhline(y=d['SIM_total'].mean(), color='r', linestyle='--') #the line I would like to alter
plt.xticks(rotation=90)
plt.title(f"Weekly Sim Count for {d['Home_Country'].iat[0]}")
plt.xlabel('Week')
a = '2020-01-13' #Key dates area
b = '2020-02-10'
plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
plt.legend()
#plt.savefig(f"{d['Home_Country'].iat[0]}_plot.png")
plt.show()
数据框包含不同的月份,但是在第 4 行上,我想绘制一条红线,显示每个国家/地区仅计算 2 月的平均值,而不是计算所有月份组合的平均值。循环中每个国家/地区的 2 月平均值会有所不同。目前我的情节是这样的:
红线的值是 1 月至 5 月的平均值,但我希望红线值显示整个 2 月的平均值。
有没有办法我可以做到这一点?
解决方案
也许您可以尝试在括号内包含一个条件?
plt.axhline(y=d[d['SIM_total'] == 'February'].mean(), color='r', linestyle='--')
我希望它有帮助!
编辑:
在那种情况下,我认为最好不要将“周”设置为索引。
你可能不是很漂亮,你可以使用下面的代码。
feb_mean = d[d['Week'] == 'February']['SIM_total'].mean()
plt.axhline(y=feb_mean, color='r', linestyle='--')
让我知道这是否适合您!
推荐阅读
- javascript - 创建一个 Javascript 投票系统
- express - connect-history-api-fallback get 无法访问
- git - 在分支主 git 状态显示没有提交(创建/复制文件并使用“git add”跟踪)
- prolog - 打印原子 Prolog 的第一个字母
- google-app-engine - Google App Engine 关闭实例并返回 500 错误
- python - 相对导入在导入的模块中不起作用
- amazon-web-services - 将 CloudFront 与没有负载均衡器的单个 EC2 实例一起使用
- ios - 为什么 React Native webview 第二次打开时加载图片失败?
- git - 在 Windows 中使用 Git 的多个 Github 帐户
- python - 正则表达式匹配字母 + 没有匹配左括号的右括号