2014-07-01 84 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

相關問題