R语言基础绘图系统
基础图形——条形图、误差图
3.条形图
barplot接收的数据是矩阵而非数据框。
data <- sample(c(50:80),5)
barplot(data,col=heat.colors(5))
my_matrix <- matrix(data=sample(10:40,9),
nrow = 3,
dimnames = list(c('A',"B",'C'),
paste('dose',1:3)))
barplot(t(my_matrix),
beside = T, #是否平行放置,F为堆栈
col = c('deeppink1','forestgreen','gray'))
更多参数用法。
par(mfrow=c(2,2))
average_gdp <- c(6500,8000,13000,9200)
country <- c('China',"Korea",'Japan',"Singapore")
barplot(average_gdp,
names.arg = country, #为条柱添加标签
horiz = F, #是否水平放置
width = c(0.5,0.6,0.8,1.0), #条柱宽度
space = 1.2) #条柱间距
4.误差条图
没有直接可用的函数来绘制误差条图。
# 误差条图
set.seed(2017)
data <- data.frame(doseA=rnorm(100,10,2),
doseB=rnorm(100,13,5),
doseC=rnorm(100,8,3))
data_mean <- apply(data,2,mean)
data_sd <- apply(data,2,sd) #标准差
barcenters <- barplot(data_mean,names.arg = names(data_mean),
ylim=c(0,20))
#存入对象中,保存的是条柱中心位置的横坐标
#以下两个都是低级绘图函数,前4个参数是起始点和终止点坐标
segments(barcenters,data_mean-data_sd,barcenters,
data_mean+data_sd,lty=1.2)
arrows(barcenters,data_mean-data_sd,
barcenters,data_mean+data_sd,
code = 3,angle = 90)#水平箭头,code两端都绘制箭头
自定义函数来绘制误差条图。
#均值和标准差是绘制误差条的基本元素
A=c(rep('drug A',10),rep('drug B',10))
B=rnorm(20,10,4)
C=rnorm(20,8,3)
D=rnorm(20,5,4)
data=data.frame(A,B,C,D)
colnames(data)=c('treatment','dose_1',"dose_2","dose_3")
#均值计算
bilan=aggregate(cbind(dose_1,dose_2,dose_3)~treatment,
data = data,mean)
rownames(bilan)=bilan[,1]
bilan=as.matrix(bilan[,-1])
lim=1.2*max(bilan)
#标准差计算
stdev=aggregate(cbind(dose_1,dose_2,dose_3)~treatment,
data=data,sd)
rownames(stdev)=stdev[,1]
stdev=as.matrix(stdev[,-1])*1.96/10
#定义函数
error.bar <- function(x,y,upper,lower=upper,length=0.1,...){
arrows(x,y+upper,x,y-lower,angle = 90,code=3,
length = length,...)
}
ze_barplot <- barplot(bilan,
beside = T,
#legend.text = T,
col = c('blue','skyblue'),
ylim = c(0,lim),
ylab = 'height')
error.bar(ze_barplot,bilan,stdev)