python - 从数据中的现有标准列添加标准偏差条?
问题描述
我正在根据以下数据(仅头部)绘制图表:
Date noctiluca_ave density_ave density_sd
0 2018-03-07 2.0 1027.514332 0.091766
1 2018-03-14 4.0 1027.339988 0.285309
2 2018-03-21 1.0 1027.346413 0.183336
3 2018-03-31 1.0 1027.372996 0.170423
4 2018-04-07 0.0 1027.292119 0.187385
如何将标准偏差 ('density_sd') 条添加到 density_ave 线?
fig, ax = plt.subplots(figsize=(10, 10))
ax.plot(hydro_weekly2 ['Date'], hydro_weekly2 ['density_ave'], label='density weekly ave', color='purple')
ax2=ax.twinx()
ax2.plot(hydro_weekly2['Date'], hydro_weekly2['noctiluca_ave'], label='noctiluca abundance' , color='r')
ax.set_ylabel('Density')
ax.set_xlabel('Date')
ax2.set_ylabel('Noctiluca abundance/cells per m3')
ax.set(title="Noctiluca Abundance and Density 2018")
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc="upper left")
解决方案
您可以替换ax.plot
为ax.errorbar()
或使用ax.fill_between()
来显示彩色条带。
这是一个包含玩具数据的示例,两种方法相结合:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
N = 20
dates = pd.date_range('2018-03-07', periods=N, freq='W-WED')
hydro_weekly2 = pd.DataFrame({'Date': dates,
'noctiluca_ave': np.random.randint(0, 14000, N),
'density_ave': 1027 + np.random.randn(N).cumsum() / 5,
'density_sd': 0.1 + np.abs(np.random.randn(N) / 5)})
fig, ax = plt.subplots(figsize=(10, 10))
ax.errorbar(hydro_weekly2['Date'], hydro_weekly2['density_ave'], yerr=hydro_weekly2['density_sd'],
label='density weekly ave', color='purple')
ax.fill_between(hydro_weekly2['Date'], hydro_weekly2['density_ave'] - hydro_weekly2['density_sd'],
hydro_weekly2['density_ave'] + hydro_weekly2['density_sd'], color='purple', alpha=0.3)
ax2 = ax.twinx()
ax2.plot(hydro_weekly2['Date'], hydro_weekly2['noctiluca_ave'], label='noctiluca abundance', color='r')
ax.set_ylabel('Density')
ax.set_xlabel('Date')
ax2.set_ylabel('Noctiluca abundance/cells per m3')
ax.set(title="Noctiluca Abundance and Density 2018")
plt.show()
推荐阅读
- linux - 将更改推送到我自己的远程存储库时出错(身份验证问题)
- javascript - ionic:如何允许多个菜单?
- r - R:在函数中使用 smooth.spline
- javascript - 如何使用 AJAX 将 PHP 数组传递给 HTML 页面?
- python - “从不太安全的应用程序访问”的解决方法
- android - 如何仅为我的 ViewHolder 获取 Json 的一部分?(在科特林)
- php - JustinRainbow/JsonSchema 中的外部引用
- javascript - 从二维数组创建 html
- python - 计算熊猫数据框中出现的次数
- android - Android Firebase 崩溃不会在第三方库(或 *.aar)中发送崩溃报告