r语言做断轴_科学网—R语言-如何在分组柱状图中添加坐标轴断轴? - 覃伟的博文...

友情提示:如果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

上一篇:再见了,凯撒斯劳滕

下一篇:大人物-比尔.盖茨

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值