2011-09-22 204 views
10

我的目標是繪製一條河流的路徑,並標出河流附近的重要地點。ggplot2中不同數據框的重疊圖

我有兩個數據幀,使河流和網站分別座標:

river<-data.frame(
    long=c(-2.816452494909265,-2.845487331898639,-2.883036393822358), 
    lat=c(56.38229290416972,56.36346886284386,56.36577994637793)) 

samploc<-data.frame(
    site=c("Site1","Site2","Site3"), 
    long=c(-2.826213585663894,-2.816519300644918,-2.868437228090127), 
    lat=c(56.3649482229089,56.38166100310631,56.36716019476281)) 

使用的老同學 - [R情節,同參數(新= T)和保護XLIM和ylim,我會得到什麼樣這樣的:

old school plot http://users.utu.fi/susjoh/Riverplot.png

但我想用GGPLOT2做到這一點。河流和點可以單獨簡單地調:

ggplot(river,aes(x=long,y=lat)) + geom_path() 
ggplot(samploc,aes(x=long,y=lat,lab=site)) + geom_point() + geom_text(vjust=2) 

我試圖作弊,通過創建與前兩次以下數據幀:

> rivsamp 
    river.long river.lat samp.site samp.long samp.lat 
1 -2.816452 56.38229  NA  NA  NA 
2 -2.845487 56.36347  NA  NA  NA 
3 -2.883036 56.36578  NA  NA  NA 
4   NA  NA  Site1 -2.826214 56.36495 
5   NA  NA  Site2 -2.816519 56.38166 
6   NA  NA  Site3 -2.868437 56.36716 

ggplot(rivsamp) + 
    geom_path(aes(x=river.long,y=river.lat)) + 
    geom_point(aes(x=samp.long,y=samp.lat)) + 
    geom_text(aes(x=samp.long,y=samp.lat,lab=samp.site),vjust=2) 

ggplot2 plot http://users.utu.fi/susjoh/riverggplot.png

它的工作原理,但創建這個新的數據框並不像舊的par(new = T)方法那麼簡單。

有沒有一種更簡單的方法來使用ggplot2從單個數據幀進行重疊繪圖?

謝謝!

+0

我會用設計來處理空間數據,即'sp'包中定義的SpatialPoints和SpatialLines類的一種方式。 –

+0

複製http://stackoverflow.com/questions/7476022/geom-point-and-geom-line-for-multiple-datasets-on-same-graph-in-ggplot2 – kmm

+1

@Kevin,不是一個確切的副本,但感謝張貼,因爲它幫助我找到答案。 – susjoh

回答

17

這裏是做

ggplot(samploc, aes(x = long, y = lat)) + 
    geom_point() + 
    geom_text(aes(label = site), vjust = 2) + 
    geom_line(data = river, aes(y = lat))