如何解决从数据中现有的std列添加标准偏差栏?
我正在基于以下数据绘制图表(仅头部):
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()
,
自此,您正在处理dataframe
。这是用density_sd
绘图显示pandas
条的另一种方法。该方法也适用于barplot。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test.csv',parse_dates=['Date'],index_col=0)
ax = df['density_ave'].plot(yerr=df['density_sd'].T)
df['noctiluca_ave'].plot(yerr=df['density_sd'].T,secondary_y=True,ax=ax)
## added errorbar in the secondary y as well.
plt.show()
输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。