友情提示:如果R代码无法正常显示,请点击原始链接查看正确代码:
问题介绍:
用barplot可以制作分组柱状图,但是无法添加断轴。
用gap.barplot可以添加断轴,但是无法制作分组柱状图。
那么如何解决这个问题呢?
请看以下案例和解决方案:
案例
# set up data
x1=c(3,5,6,9,375,190);
x1
x2=c(2,2,3,30,46,60);
x2
data=rbind(x1,x2);
data
colnames(data)=c("Pig","Layer","Broiler","Dairy","Beef","Sheep")
rownames(data)=c("1980","2010")
data
# plot grouped bar by using barplot
barplot(data,
beside=T,
ylab="Number of animal",
#cex.names=0.8,
#las=2,
col=c("darkblue","red")
)
# Since there are large differences in numbers,so I want to add a break between 200 to 340 as below:
data_T=t(data);
data_T
#install.packages("reshape")
library(reshape)
mdata
mdata
colnames(mdata)=c("Animal","Year",'value');
mdata
gap.barplot(mdata$value,
gap=c(200,340),
xlab="Animal",
ytics=c(0,50,100,150,200,300,350,400),
ylab="Number of animal",
xaxlab=mdata$Animal,
xaxt="n")
#xaxt="n"is esential to remove everything from x axis (e.g. a clean x axis)
# then define a axis using the following
axis(side = 1, at = seq_along(mdata$Animal),mdata$Animal,tick = FALSE)
abline(h=seq(200,205,.001), col="white") # hiding vertical lines
axis.break(axis=2,breakpos=202.5,style="slash") # break the left Y axis
解决方案,见Jim Lemon给我的回信,如下:
Hi Wei, The gap.barplot function doesn't do grouped bars (yet). You can probably get what you want with this:
#install.packages("plotrix") # only need to install once
library(plotrix)
newdata
newdata[newdata>200]200]-140
barpos
ylim=c(0,250),beside=TRUE,col=c("darkblue","red"),axes=FALSE)
axis(2,at=c(0,50,100,150,200,235),
labels=c(0,50,100,150,200,375))
box()
axis.break(2,210,style="gap")
Jim
致谢:
Great thanks to Jim Lemon, the author of gap.barplot, for his kind help!
Wei
转载本文请联系原作者获取授权,同时请注明本文来自覃伟科学网博客。
链接地址:http://blog.sciencenet.cn/blog-569569-798390.html
上一篇:再见了,凯撒斯劳滕
下一篇:大人物-比尔.盖茨