簡體   English   中英

如何使用 python 制作帶有誤差線的 plot 條形圖?

[英]How do I plot bar graphs with error bars using python?

我正在使用 Python 3.5。 此外,我是初學者(3 周經驗)Python 嘗試者,不知何故我沒有放棄嘗試分析我的數據。

數據說明:我的數據在一個csv文件(fev.csv)中。 如果您想查看完整數據集的完整范圍,我已將其包含在此處。 它有 5 列:

  • 年齡(歲)
  • fev(升)
  • 高(英寸)
  • 性別(女=0,男=1)
  • 吸煙(非吸煙者=1,吸煙者=1)

任務:我正在嘗試編寫一個程序來生成平均 FEV 的條形圖,其中誤差條表示標准偏差。 我試圖在 4 個不同的年齡類別(11-12、13-14、15-16、17 或更大)獲得 2 個並排的酒吧(吸煙者/非吸煙者)。

到目前為止的代碼(請原諒我所有的#notes,它幫助我知道我想做什么):

import numpy as np

import matplotlib.pyplot as plt

import pandas as pd



data = pd.read_csv('fev.csv')



nonsmokers = data[data.smoke==0]

smokers = data[data.smoke==1]



nonsmokers1 = nonsmokers[(nonsmokers.age==11) | (nonsmokers.age==12)]

nonsmokers2 = nonsmokers[(nonsmokers.age==13) | (nonsmokers.age==14)]

nonsmokers3 = nonsmokers[(nonsmokers.age==15) | (nonsmokers.age==16)]

nonsmokers4 = nonsmokers[(nonsmokers.age>=17)]



smokers1 = smokers[(smokers.age==11) | (smokers.age==12)]

smokers2 = smokers[(smokers.age==13) | (smokers.age==14)]

smokers3 = smokers[(smokers.age==15) | (smokers.age==16)]

smokers4 = smokers[(smokers.age>=17)]



nonsmMean = [nonsmokers1.fev.mean(), nonsmokers2.fev.mean(), nonsmokers3.fev.mean(), nonsmokers4.fev.mean()]

nonsmSd = [nonsmokers1.fev.std(), nonsmokers2.fev.std(), nonsmokers3.fev.std(), nonsmokers4.fev.std()]

smMean = [smokers1.fev.mean(), smokers2.fev.mean(), smokers3.fev.mean(), smokers4.fev.mean()]

smSd = [smokers1.fev.std(), smokers2.fev.std(), smokers3.fev.std(), smokers4.fev.std()]



# data to be plotted

nonsmoker = np.array(nonsmMean)

sdNonsmoker = np.array(nonsmSd)

smoker = np.array(smMean)

sdSmoker = np.array(smSd)



# parameters

bar_width = 0.35

x = np.arange(len(nonsmoker))



# plotting bars

plt.bar(x, nonsmoker, bar_width, yerr=sdNonsmoker, ecolor='k', color='b', label='Nonsmokers')

plt.bar(x+bar_width, smoker, bar_width, yerr=sdSmoker, ecolor='k', color='m', label='Smokers')



# formatting and labeling the axes and title

plt.xlabel('Age')

plt.ylabel('FEV')

plt.title('Mean FEV by Age and Smoking Status')



plt.xticks(x+0.35, ['11 to 12', '13 to 14', '15 to 16', '17+'])



# adding the legend

plt.legend()



plt.axis([-0.5,4.2,0,7])



plt.savefig('FEVgraph.png', dpi=300)


# and we are done!

plt.show() 

有沒有更有效的方法來做到這一點?

謝謝!

可能的解決方案如下:

# pip install pandas
# pip install matplotlib

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

# read csv file and create pandas dataframe
df = pd.read_csv('https://raw.githubusercontent.com/benkeser/halplus/master/inst/extdata/fev.csv')

# assign age bins to data
bins = [df['age'].min()-1, 10, 12, 14, 16, df['age'].max()]
bins_labels = ['<11', '11 to 12', '13 to 14', '15 to 16', '17+']
df['age_bins'] = pd.cut(df['age'], bins, labels = bins_labels)

# aggregate data
result = df.groupby(['smoke', 'age_bins'], as_index=False).agg({'fev':['mean','std']})
result.columns = ['_'.join(col).strip('_') for col in result.columns.values]
result = result.round(1)

# prepare data for plot
nonsmokers = result[result['smoke'] == 0]
smokers = result[result['smoke'] == 1]
x = np.arange(len(bins_labels))
width = 0.35

# set plot fugure size
plt.rcParams["figure.figsize"] = [8,6]


fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, nonsmokers['fev_mean'], width, yerr=nonsmokers['fev_std'], color='b', label='Nonsmokers')
rects2 = ax.bar(x + width/2, smokers['fev_mean'], width, yerr=smokers['fev_std'], color='m', label='Smokers')

ax.set_xlabel('Age')
ax.set_ylabel('FEV')
ax.set_title('Mean FEV by Age and Smoking Status')
ax.set_xticks(x, bins_labels)
ax.legend(loc=2)

fig.tight_layout()

plt.savefig('FEVgraph.png', dpi=300)

plt.show()

退貨

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM