简体   繁体   中英

r - Ploting two plots (3 variables) with one x-axes in ggplot

I am trying to plot two flows and one rainfall data in one graph. I have broke it up into top and bottom parts as shown in the following pic. Here I have two issues with this plots and spent ages but cannot solve it.

  1. Why the observed flow always in black, even I have set it up as blue? Did I accidentally used some other arguments to overwrite it?
  2. The most importantly is, how do I able to add a legend for the bottom plot? I tried many different codes but they don't seem to work for me.

     x = data.frame(date = Date, rain = Obs_rain, obsflow = Obs_flow,simflow=Sim_flow) g.top <- ggplot(x, aes(x = date, y = rain, ymin=0, ymax=rain)) + geom_linerange() + scale_y_continuous(trans = "reverse") + theme_bw() + theme(plot.margin = unit(c(1,5,-30,6),units="points"), axis.title.y = element_text(vjust =0.3)) + labs(x = "Date",y = "Rain(mm)") g.bottom <- ggplot(x, aes(x = date, y = obsflow, ymin=0, ymax=obsflow), colour = "blue",size=0.5) + geom_linerange() + #plot flow geom_linerange(aes(y = simflow, ymin=0, ymax=simflow), colour = "red", size =0.5)+ labs(x = "Date", y = "River flow (ML/day)") + theme_classic() + theme(plot.background = element_rect(fill = "transparent"), plot.margin = unit(c(2,0,1,1),units="lines")) grid.arrange(g.top,g.bottom, heights = c(1/5, 4/5)) 

    在此处输入图片说明

Update:

I have resolved the issue with blue line colour. I accidently put arguments in the wrong place. But I'm still struggling with the legend.

    g.bottom <- ggplot(x, aes(x = date, y = obsflow, ymin=0, ymax=obsflow)) +
                geom_linerange(colour = "blue",size=0.5) +  #plot flow

As an explanation of what @pierre means... turn your data from "wide" to "long" format using reshape2::melt , so that the flow type for each date is in one column flow_type , and the value is another ( flow_val ). Then you specify flow_type as the grouping variable with which to assign colour:

require(reshape2)

x.melted <- melt(x, id.vars = c("date", "rain"), variable.name="flow_type",
                 value.name="flow_val")

g.bottom <- ggplot(x.melted, aes(x = date),size=0.5) +
  geom_linerange(aes(ymin=0, ymax=flow_val, colour=flow_type)) +  #plot flow
  labs(x = "Date", y = "River flow (ML/day)") +
  theme_classic() +
  theme(plot.background = element_rect(fill = "transparent"),
        plot.margin = unit(c(2,0,1,1),units="lines"), 
        legend.position="bottom") + 
  scale_colour_manual(guide = guide_legend(title = "Flow Type"), 
                      values = c("obsflow"="blue", "simflow"="red"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM