首页 > 解决方案 > 切换轴时错误地移动了第二轴;ggplot

问题描述

我正在创建一个带有 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))

正确的 y 轴

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

我错过了什么吗?

#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)))

y轴错误

标签: rggplot2

解决方案


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

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

第二个代码块

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

但是您将主 y 轴从 更改preca+prec*b。所以事情已经过去了。

如果你只是想换边,scale_y_continuous有一个参数position = "left",你应该可以设置"right"(我希望辅助会自动出现)。

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


推荐阅读