使用numpy的标准偏差?

2024-04-25 18:22:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何从我的数据中用误差条和/或灰色区域(有点像置信区间)绘制标准偏差。它包含跨多天的多个主题的数据。我已经看到了几行有助于解释的代码,但我在尝试将代码放入时遇到了困难。我知道代码使用numpy,但是我在这个图的大部分部分都使用了matplot,所以我不知道如何翻译它(对于这个还是相当新的)

进一步澄清:共有九个受试者,每个受试者的准确率在50%-100%之间。数据在excel中编译,excel中有一行“天”(1-22)和“主题”(在给定的日期具有相应的准确性,即第1天为50%,第2天为65%,等等)

以下是我找到的代码行:

# Calculate the standard deviation of datasets
stdv_data=np.std(data)

# Create an error bar for each dataset
line_stdv=ax.errorbar(xaxis, data, yerr=STDV_data)

这是我的密码:

import pandas as pd 
import matplotlib.pyplot as plt
import numpy as np

#sketched code
df = pd.read_excel('Behavioraldata.xlsx')

plt.figure(figsize=(10, 7))
Day = df['Day']
Accuracy = df[['1', '2', '3', '4', '5', '6', '7', '8', '9']]
plt.plot(Day, Accuracy, alpha = 0.4)
Accuracy_mean = df[['1', '2', '3', '4', '5', '6', '7', '8', '9']].mean(axis=1)
plt.plot(Day, Accuracy_mean, color = "black", marker="s")
plt.axis([1, 22, 0.55, 1])
plt.axhline(y=0.8, color='black', linestyle='--', alpha=0.5)
plt.xlabel('Day')
plt.ylabel('Accuracy')
plt.title("Days to Acquisition by Rat")
ax = plt.subplot()
ax.set_xticks(Day)
plt.show()

我尝试格式化代码,使其符合我的要求:

stdv_accuracy_mean=np.std(accuracy_mean)

line_stdv=ax.errorbar(xaxis, accuracy_mean, yerr=stdv_accuracy_mean)

但是没有用。任何帮助都将不胜感激

到目前为止,我的图表是这样的: 1

我希望它看起来像这些线程中的图:12


Tags: 数据代码importdfdataasnpplt
2条回答

根据你所写的,我认为缺少的部分是pyplot.fill_between()

伪造一些数据我得到了这个

from matplotlib import pyplot as plt
import numpy as np

# fake up some data
x = np.linspace(1, 22, 22)
y = np.linspace(.50, 1.0, 22)
errorbar = np.random.normal(.25, .1, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)


plt.plot(x, y, 'k-')
plt.fill_between(x, y-errorbar, y+errorbar)
plt.show()

enter image description here

errorbar已经为您画好了线,所以您不需要两个命令。相反,您可以这样做:

fig, ax = plt.subplots(figsize=(15,10))

std_data = np.std(Accuracy_mean)
ax.errorbar(Day, Accuracy_mean, yerr=std_data, color='k', marker='s', ecolor='C0')

输出:

enter image description here

相关问题 更多 >