ggplot中辅助轴的正确公式

时间:2019-08-23 12:40:31

标签: r ggplot2 yaxis

我想在R中使用带有辅助轴的ggplot绘制以下数据,但是无法正确地将其添加到图中。 我将不胜感激。

dat <- structure(list(Year = 1998:2012, active_rain = 
c(13.8036796536796, 
29.6755102040816, 18.5603174603175, 28.7833333333333, 19.631746031746, 
41.1738095238095, 15.2059523809524, 21.76, 6.99764705882353, 
14.96, 26.5134615384615, 24.4257142857143, 14.528, 15.23, 
14.5704347826087
), break_rain = c(3.09523809523809, 1.77714285714286, 
0.847619047619049, 
1.5952380952381, 1.01904761904762, 0.985185185185186, 
1.20416666666667, 
0.4875, 1.18285714285714, 1.556, 3.2, 3.26, 2.805, 0.95, 1.49
), duration = c(11L, 7L, 18L, 6L, 18L, 14L, 14L, 15L, 17L, 9L, 
13L, 7L, 5L, 8L, 23L), bduration = c(3L, 5L, 6L, 7L, 6L, 6L, 
4L, 4L, 7L, 5L, 7L, 4L, 4L, 8L, 4L), break_hgt = c(1509L, 1505L, 
1505L, 1509L, 1504L, 1496L, 1514L, 1490L, 1511L, 1505L, 1496L, 
1499L, 1506L, 1509L, 1506L)), class = "data.frame", row.names = c(NA, 
-15L))

这是我的剧本:

library(ggplot2)
dat<-read.csv("summary_break.csv",header = TRUE,sep = ",")
dat<-data.frame(dat)
p <- ggplot(dat, aes(x=Year))
p <- p + geom_line(aes(y=break_rain),colour="red")
p <- p + geom_point(aes(y=break_rain),colour="red",pch=21,fill="blue",size=0.5)
p <- p + geom_line(aes(y=(break_hgt-1475),colour="blue"))
p <- p + geom_point(aes(y=(break_hgt-1475)),colour="blue",pch=21,fill="blue",size=0.5)
p <- p + scale_y_continuous(breaks=seq(0,3.5,by=0.5),limits=c(0,3.5),sec.axis = sec_axis(~.+1475,name=bquote("HGT")))
p <- p + theme(panel.background=element_rect(fill="white"),
         panel.border=element_rect(colour="black",fill=NA,size=1),
         #panel.grid.major.x = element_line(color = "grey80",size=0.25),
         axis.line.x=element_line(colour="black"),
         axis.line.y=element_line(colour="black"),
         axis.text=element_text(colour="black",size=10,family="serif"),
         axis.title=element_text(colour="black",size=10,family="serif"),
         legend.position="none",legend.key = element_rect(fill = 'white'),
         plot.margin=unit(c(0.5,0.5,0.5,0.5),"cm"))

p <- p + scale_x_continuous(breaks=seq(1998,2012,by=1),limits=c(1998,2012),expand=c(0,0))
p <- p + labs(x = "Year", y = bquote("Rainfall"))

outImg <- paste0("hgt_ushear",".jpg")
ggsave(outImg,p,width=6,height=4)

脚本的输出: enter image description here

预期输出:

预期输出应如下所示: enter image description here

1 个答案:

答案 0 :(得分:1)

这不是ggplot解决方案,而是base R解决方案!可能对您有帮助!

par(mar=c(5.1, 4.1, 4.1, 4.1))
plot(dat$Year, dat$break_rain, type = "o", col="red", xlab="Year", ylab="Railfall") 
par(new = TRUE)
plot(dat$Year, dat$break_hgt, type = "o", col="blue", axes = FALSE, xlab = "", ylab = "")
axis(side=4, at = c(1475,1483,1491,1499,1507,1515))
mtext("hgt", side=4, line=2.5)

enter image description here