轴切换时错误移动第二轴;绘图

时间:2021-02-01 07:35:00

标签: r ggplot2

我正在创建一个带有 2 个 y 轴的图,我在其中组合了折线图和柱形图。 这样,它看起来应该是这样的:

#definition of dummy data set
set.seed(1)
n<-30
prec1 <-round(runif(n, min=0, max=4),0)
prec2 <-round(runif(n, min=0, max=0),0)
depth1 <- runif(n, min=-0.3, max=0)
depth2 <- runif(n, min=-0.1, max=0.1)
date  <- seq(1,n,1)
id <- c(rep("P-05",n), rep("PR-07",n))

dat <- data.frame("date" = c(date,date),
                 "id" = id,
                 "prec" = c(prec1,prec2),
                 "depth" = c(depth1,depth2))


#definition of axis limiters
ylim.prim <- c(0, 4) 
ylim.sec <- c(-0.3,0.1) 
b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])

ggplot()+
  geom_col(data=dat,aes(x=date,y=prec))+
  geom_line(data=dat,aes(x=date,y=a+depth*b,colour=factor(id)))+
  scale_y_continuous("precipitation",breaks=seq(0,4,by=0.5),
                     sec.axis = sec_axis(~ (. - a)/b, name = "depth",
                                         breaks=seq(-0.3,0.1,by=0.05),
                                         labels=comma))

correct y-axes

但是,当将 y-left 和 y-right 轴切换时,一个轴会移动到图的下部。

我错过了什么吗?

#definition of axis limiters
ylim.prim <- c(-0.3,0.1) 
ylim.sec <- c(0, 4) 
b <- diff(ylim.prim)/diff(ylim.sec)
a <- b*(ylim.prim[1] - ylim.sec[1])

ggplot()+
  geom_col(data=dat,aes(x=date,y=a+prec*b))+
  geom_line(data=dat,aes(x=date,y=depth,colour=factor(id)))+
  scale_y_continuous("depth",breaks=seq(-0.3,0.1,by=0.05),labels=comma,
                     sec.axis = sec_axis(~ (. - a)/b, name = "precipitation",
                                         breaks=seq(0,4,by=0.5)))

wrong y-axes

1 个答案:

答案 0 :(得分:0)

您忘记更改第二个代码中的转换。第一个代码块

sec.axis = sec_axis(~ (. - a)/b, name = "depth",

第二个代码块

sec.axis = sec_axis(~ (. - a)/b, name = "precipitation",

但是您将主 y 轴从 prec 更改为 a+prec*b。所以事情已经结束了。

如果您只是想换边,scale_y_continuous 有一个参数 position = "left",您应该可以将其设置为 "right"(我希望次要会自动显示为左) .

http://127.0.0.1:10092/library/ggplot2/html/scale_continuous.html