Matplotlib学习---用matplotlib画误差线(errorbar)
誤差線用于顯示數(shù)據(jù)的不確定程度,誤差一般使用標(biāo)準(zhǔn)差(Standard Deviation)或標(biāo)準(zhǔn)誤差(Standard Error)。
?
標(biāo)準(zhǔn)差(SD):是方差的算術(shù)平方根。如果是總體標(biāo)準(zhǔn)差,那么用σ表示,如果是樣本標(biāo)準(zhǔn)差,那么用s表示。標(biāo)準(zhǔn)差反映數(shù)據(jù)集的離散程度,標(biāo)準(zhǔn)差越小,就說明數(shù)據(jù)越集中在其平均值附近。公式:(總體),(樣本) 標(biāo)準(zhǔn)誤差(SE):是樣本分布的標(biāo)準(zhǔn)差。如果是樣本平均數(shù)分布的標(biāo)準(zhǔn)差,那么就稱為SEM(standard error of the mean),就是說每次從總體中抽取n個(gè)樣本,抽取很多次后,每次抽樣的平均值(?)就形成了一個(gè)數(shù)據(jù)分布,這個(gè)數(shù)據(jù)分布有自己的平均值和標(biāo)準(zhǔn)差。抽樣的平均值分布的平均數(shù)應(yīng)該接近總體平均數(shù)(?μ)。標(biāo)準(zhǔn)誤差反映樣本(sample)對(duì)于總體(population)的差異性,每次抽樣的樣本數(shù)越多,標(biāo)準(zhǔn)誤差就越小。公式:?
下面利用Nathan Yau所著的《鮮活的數(shù)據(jù):數(shù)據(jù)可視化指南》一書中的數(shù)據(jù),學(xué)習(xí)畫圖。
?
數(shù)據(jù)地址:http://datasets.flowingdata.com/crimeRatesByState2005.csv
?
以下是這個(gè)數(shù)據(jù)文件的前5行:
state murder forcible_rape robbery aggravated_assault \ 0 United States 5.6 31.7 140.7 291.1 1 Alabama 8.2 34.3 141.4 247.8 2 Alaska 4.8 81.1 80.9 465.1 3 Arizona 7.5 33.8 144.4 327.4 4 Arkansas 6.7 42.9 91.1 386.8 burglary larceny_theft motor_vehicle_theft population 0 726.7 2286.3 416.7 295753151 1 953.8 2650.0 288.3 4545049 2 622.5 2599.1 391.0 669488 3 948.4 2965.2 924.4 5974834 4 1084.6 2711.2 262.1 2776221這是美國(guó)各州各種犯罪行為的發(fā)生率(每10萬人口)。
?
讓我們畫一個(gè)圖,把全美各犯罪率的平均數(shù),標(biāo)準(zhǔn)差展現(xiàn)出來。
?
誤差線: ax.errorbar(x,y,yerr=error size in y axis,xerr=error size in x axis)
?
代碼如下:
import numpy as np import pandas as pd from matplotlib import pyplot as plt crime=pd.read_csv(r"http://datasets.flowingdata.com/crimeRatesByState2005.csv") fig,ax=plt.subplots(figsize=(8,4))col=crime.columns.astype(str) #提取列名,將來做x軸刻度標(biāo)簽 crime=crime[1:] #把第一行US的數(shù)據(jù)去除 data=crime.loc[:,"murder":"motor_vehicle_theft"] #提取數(shù)據(jù)部分,以便將來進(jìn)行計(jì)算 crime.loc["mean"]=data.apply(np.mean) #增加一行,為數(shù)據(jù)每列的均值,apply函數(shù)用于數(shù)據(jù)每一列 crime.loc["standard deviation"]=data.apply(np.std) #增加一行,為數(shù)據(jù)每列的標(biāo)準(zhǔn)差,apply函數(shù)用于數(shù)據(jù)每一列#畫誤差線,x軸一共7項(xiàng),y軸顯示平均值,y軸誤差為標(biāo)準(zhǔn)差 ax.errorbar(np.arange(7),crime.loc["mean","murder":"motor_vehicle_theft"],\yerr=crime.loc["standard deviation","murder":"motor_vehicle_theft"],\fmt="o",color="blue",ecolor='grey',elinewidth=2,capsize=4) ax.set_xticklabels(col,rotation=45) #設(shè)置x軸刻度標(biāo)簽,并使其傾斜45度,不至于重疊 plt.show()?
圖像如下:
?
?
另外,還可以在柱形圖或條形圖上畫誤差線,分別在ax.bar命令里加上yerr參數(shù),或在ax.barh命令里加上xerr參數(shù)即可。
?
轉(zhuǎn)載于:https://www.cnblogs.com/HuZihu/p/9418903.html
總結(jié)
以上是生活随笔為你收集整理的Matplotlib学习---用matplotlib画误差线(errorbar)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 涂鸦蓝牙SDK开发系列教程——4.烧录授
- 下一篇: 干货|一文看懂BLE低功耗技术-附主流B