10

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

Using an old school R plot, with par(new=T) and conserving xlim and ylim, I would get something like this:

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

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 plot http://users.utu.fi/susjoh/riverggplot.png

It works, but creating this new data frame is not as straightforward as the old par(new=T) method.

Is there a simpler way to overplot from the individual data frames using ggplot2?

Thanks!

3
  • I would use classes designed to handle spatial data, namely SpatialPoints and SpatialLines that are defined in sp package. Commented Sep 22, 2011 at 14:17
  • Duplicate of stackoverflow.com/questions/7476022/… Commented Sep 22, 2011 at 14:17
  • 1
    @Kevin, not an exact duplicate, but thanks for posting as it helped me to find the answer. Commented Sep 22, 2011 at 14:36

1 Answer 1

17

Here is one way to do it

ggplot(samploc, aes(x = long, y = lat)) + 
  geom_point() + 
  geom_text(aes(label = site), vjust = 2) + 
  geom_line(data = river, aes(y = lat))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.