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

前端 未结 1 995
温柔的废话
温柔的废话 2021-01-16 07:27

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 thi

1条回答
  •  不思量自难忘°
    2021-01-16 08:03

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

    0 讨论(0)
提交回复
热议问题