r - 在ggplot中用一个x轴绘制两个图(3个变量)

时间:2014-07-01 00:47:44

标签: r graph plot ggplot2

我试图在一个图中绘制两个流量和一个降雨量数据。我把它分成了顶部和底部,如下图所示。在这里,我有两个问题与这个情节和花了很多年,但无法解决它。

  1. 为什么观察到的流量始终为黑色,即使我将其设置为蓝色?我是否意外地使用了其他一些参数来覆盖它?
  2. 最重要的是,我如何为底部情节添加图例?我尝试了许多不同的代码,但它们似乎并不适合我。

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

    enter image description here

  3. 更新:

    我用蓝线颜色解决了这个问题。我意外地把论点放在了错误的地方。但我仍然在与传奇作斗争。

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

1 个答案:

答案 0 :(得分:2)

作为对@pierre意味着什么的解释......将数据从&#34;宽&#34;到&#34;长&#34;使用reshape2::melt格式化,以便每个日期的流类型位于一列flow_type中,值为另一列(flow_val)。然后指定flow_type作为分配变量的分组变量:

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