GGplot2 双 y 轴并切换覆盖层,同时保持轴位置

问题描述 投票:0回答:1

我正在接手一个项目,其中所有数字都是在 Excel 中创建的,我现在正尝试在 ggplot2 中重新创建它们以供将来的报告使用。我正在绘制双 y 轴图,以直观地表示该地点降雨量高的时间与当时水深之间的关系。以下是我们的数据的组成样本。我想将左轴和右轴保持在相同的位置(左仍然是左,右仍然是右),但我希望这些线覆盖在条形的顶部而不是像现在一样位于后面。我可以通过将右轴设置为左轴来轻松解决此问题,但为了与前几年的连续性,我不想这样做。谢谢你或者你的帮助。下面是我的代码和一些虚拟数据:

library(ggplot2)
library(dplyr)
library(lubridate)

Date <- c("2021-01-01","2021-01-01", "2021-01-05", "2021-01-05","2021-01-10", "2021-01-10", "2021-01-15","2021-01-15") 
Rainfall <- c(0.75, 0.5, 0.63, 0.9,0.5, 0.63, 0.9,0.6)
Pool <- c("A","B","A","B","A","B","A","B")
WaterDepth <- c(18,22,17,19,15,24,13,11)
Var4 <- c(1000, 987,905,1002)

nine <- data.frame(Date, WaterDepth,Pool,Rainfall, Var4)
nine<-nine %>% mutate(Date = ymd(Date))

nine

scale2=.05
figa <- ggplot()  +  
  geom_line(aes(x=nine$Date,y = nine$WaterDepth, color=nine$Pool),linewidth=1.5)+ 
  geom_col(aes(x=nine$Date, y = nine$Rainfall/scale2,fill="Rainfall"),width=1,alpha=1)+ 
  scale_fill_manual(values = c("#0070C0"))+
  scale_color_manual(values=c("#C55A11","#99CC00"))+
  labs(
    x="Date",y="Water Depth (cm)")+ 
  scale_y_continuous(sec.axis = sec_axis(~.*scale2, name="Rainfall (cm)"),expand=c(0,0),limits=c(0,30)) +
  theme(legend.position="bottom",
        legend.title=element_blank(),
        legend.key.width=unit(.5,"cm"),
        legend.key.height=unit(.2,"cm"))+
  theme(axis.line = element_line(colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        axis.text=element_text(size=10),
        axis.title=element_text(size=13))+
  labs(color = "Legend")

figa
r ggplot2
1个回答
0
投票
ggplot(nine)  +  
  geom_col(aes(x=Date, y = Rainfall/scale2, fill="Rainfall"), width=1)+ 
  geom_line(aes(x=Date, y = WaterDepth, color=Pool), linewidth=1.5)+ 
  ...

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.