我有一个数据框,其中包含四列,如下所示(这里只放出了我的实际数据框的标题):
我该如何绘制数据图表,以便在主轴上绘制变量
df <- tibble(Date=c("2007-05-01", "2007-05-02","2007-05-03", "2007-05-04", "2007-05-05"), Obs = c(0.16,0.15,0.17,0.19,0.14), Sim = c(0.17, 0.11, 0.21, 0.15, 0.13), Rain = c(0.1, 0.11, 0.04,0.21,0.5))
我该如何绘制数据图表,以便在主轴上绘制变量
Obs
和Sim
,并将Rain
绘制为反向次要轴上的条形图?以下是到目前为止我尝试过的代码:ggplot(df, aes(x=as.Date(Date))) +
geom_line(aes(y=Obs, color="red")) +
geom_line(aes(y=Sim, color="green")) +
geom_bar(mapping = aes(y = Rain), stat = "identity") +
scale_y_continuous(name = expression('Soil moisture, m'^"3"*' m'^"-3"),
sec.axis = sec_axis(~ 3 - .*0.5, name = "Precipitation (inch)"))
这是我期望的输出结果:
编辑:此外,我如何插入与每条线对应的图例(即Obs、Sim和Rain)?