r - 切换轴时错误地移动了第二轴;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-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)))
解决方案
您忘记更改第二个代码中的转换。第一个代码块
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
推荐阅读
- html - Vue中如何将图像作为组件模板,以src作为属性
- selenium - 如何使用 Selenium 检查样式为复选框的输入跨度?只有 :: after 作为状态之间的差异
- android - 对于 Imgur API,Google OAuth 似乎已损坏
- excel - 无法在 FormatConditons 中分配 IconSet 属性
- react-native - ScrollToIndex 没有按预期滚动 FlatList
- python - 如何将大小为 1 的字符串转换为 Dataframe?
- pandas - 将索引转换为 Pandas 列
- php - 表单中的此集合中不存在属性 [id]
- google-apps-script - 可以优化慢速过滤/排序脚本以更快地运行吗?
- android - Android webview 在最新的 android 版本中不起作用