LauraC
LauraC

Reputation: 55

How to annotate R map with text and points

I have some data that looks like this:

>show(recruitment_info)
Centre      Lat      Long      GroupA     GroupB
1    CentreA 51.51770 -0.100400         907         47
2    CentreB 52.48947 -1.898575        1910        116
3    CentreC 51.45451 -2.587910        4419        277

I want to plot a map of the UK and then add points for each centre (labelled with Centre in column 1). I also want the point size to represent the values in GroupA and GroupB - I don't mind if GroupA and GroupB need to separate plots, that I then align horizontally.

I have tried using map_data and map.

UK <- map_data(map = "world", region = "UK")
ggplot(data = UK, aes(x = long, y = lat, group = group)) + 
  geom_polygon() +
  coord_map() +
  geom_point(aes(x=recruitment_info$Long,y=recruitment_info$Lat)) +
  geom_text(aes(label=recruitment_info$Centre),hjust=0, vjust=0)
UK <- map('worldHires',c('UK','Ireland'), xlim=c(-11,3), ylim=c(49,60.9))
ggplot(data = UK, aes(x = x, y = y)) +
  geom_point(aes(x = recruitment_info$Long, y = recruitment_info$Lat),col=2,pch=18)

Unfortunately I cannot get it to work for me.

If anyone is able to help, I would really appreciate it!

Thank you

Upvotes: 2

Views: 4647

Answers (1)

Arienrhod
Arienrhod

Reputation: 2581

there were several things that were not really correct within your code.

  1. You have to provide the data explicitly for additional layers using the data argument.
  2. In order to vary the point size through groups, you have to reshape your data and cast it into the long format (so your GroupA and GroupB columns collapse into Group and values column).

In general, when submitting questions to SO, show your data using dput as this is much easier to work with and test the code than the output of head.

recruitment_info <- data.frame(Centre = c("CentreA", "CentreB", "CentreC"),
                               Lat = c(51.51770, 52.48947, 51.45451),
                               Long = c(-0.100400, -1.898575, -2.587910),
                               GroupA = c(907, 1910, 4419),
                               GroupB = c(47, 116, 277), stringsAsFactors = FALSE)

recruitment_info <- recruitment_info %>% 
  gather(Group, values, -Centre, -Lat, -Long)

UK <- map_data(map = "world", region = "UK")
ggplot(data = UK, aes(x = long, y = lat, group = group)) + 
  geom_polygon(fill="grey") +
  coord_map() +
  geom_point(data = recruitment_info, aes(x=Long, y=Lat, group=Centre, size=values)) +
  geom_text(data = recruitment_info, aes(x=Long, y=Lat, group=Centre, label=Centre), size = 3, hjust=0, vjust=-1) +
  facet_grid(cols = vars(Group))

example

This is a very basic plot and you can definitely prettify it using different colours for the centres, maybe different breaks for the group size, etc.

Upvotes: 3

Related Questions