从ggplot2中的不同数据帧过度绘图 [英] Overplotting from different data frames in ggplot2
问题描述
我的目标是绘制一条河流的路径,并用点表示河流附近的重要地点.
My objective is to plot the path of a river with points indicating important sites near the river.
我有两个数据框,分别给出了河流和地点的坐标:
I have two data frames, giving the river and site coordinates respectively:
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))
使用带有par(new = T)并保留xlim和ylim的旧式R图,我会得到这样的东西:
Using an old school R plot, with par(new=T) and conserving xlim and ylim, I would get something like this:
旧校区http://users.utu.fi/susjoh/Riverplot.png
但是我想使用ggplot2做到这一点.河流和景点可以轻松地单独调用:
But I would like to do it using ggplot2. The river and points can be easily called individually:
ggplot(river,aes(x=long,y=lat)) + geom_path()
ggplot(samploc,aes(x=long,y=lat,lab=site)) + geom_point() + geom_text(vjust=2)
我试图通过从前两个创建以下数据框来作弊:
I have tried to cheat, by creating the following data frame from the previous two:
> 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情节http://users.utu.fi/susjoh/riverggplot.png
它可以工作,但是创建这个新的数据帧并不像旧的par(new = T)方法那样简单.
It works, but creating this new data frame is not as straightforward as the old par(new=T) method.
是否有更简单的方法使用ggplot2从各个数据帧中进行过度绘制?
Is there a simpler way to overplot from the individual data frames using ggplot2?
谢谢!
推荐答案
这是一种实现方法
ggplot(samploc, aes(x = long, y = lat)) +
geom_point() +
geom_text(aes(label = site), vjust = 2) +
geom_line(data = river, aes(y = lat))
这篇关于从ggplot2中的不同数据帧过度绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!