2014-07-01 80 views
1

我想在一个图中绘制两个流量和一个降雨量数据。我已经分解成顶部和底部部分,如下图所示。在这里,我有两个问题与这个情节,花了几年,但无法解决它。r - 在ggplot中用一个x轴绘制两个图(3个变量)

  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

更新:

我已经解决了与蓝线颜色的问题。我无意中将论点置于错误的地方。但我仍然在为这个传奇而努力。

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

用于底部绘图。融化您的数据,即您应该有3列:1 =日期,2 =流量(obs vs sim),3 =值。然后用aes(x = data,y = value,color = flow) – Pierre

+0

嗨,皮埃尔,我不确定你说3列时:1 =日期,2 =流量(obs vs sim),3 =值。你能否解释一下第二或第三栏的含义? –

回答

2

由于@pierre意思的解释...把你从“宽”的数据,“长”格式使用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")) 
+0

非常感谢,我非常感谢。但我也很好奇,如果我想使用不同的线型,我只在'color = flow_type'之后添加'linetype = flow_type',但我怎样才能在一个插槽中绘制图例?现在它是一种颜色和一种线型的传说。 –

+0

试试这个答案:http://stackoverflow.com/questions/12410908/creating-a-ggplot-legend-with-both-color-and-shape – andyteucher

相关问题