覃伟的博客分享 http://blog.sciencenet.cn/u/WeiQin 分享、学习、进步

博文

R语言-如何在分组柱状图中添加坐标轴断轴?

已有 13499 次阅读 2014-5-28 16:25 |系统分类:科研笔记| weiqin

友情提示:如果R代码无法正常显示,请点击原始链接查看正确代码

http://stackoverflow.com/questions/23884991/how-to-add-break-in-axis-for-grouped-barplot


问题介绍:

用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 <- melt(data_T, id=c("1980","2010"));

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<-data

newdata[newdata>200]<-newdata[newdata>200]-140

barpos<-barplot(newdata,names.arg=colnames(newdata),

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



https://blog.sciencenet.cn/blog-569569-798390.html

上一篇:再见了,凯撒斯劳滕
下一篇:大人物-比尔.盖茨
收藏 IP: 137.224.252.*| 热度|

1 黄仁勇

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-12-23 04:21

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部