Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when trying to plot points on a map

Tags:

r

mapping

ggplot2

I'm trying to plot points on a map of the UK, where the size of the points changes depending on the data.

Here is part of my data file (this is my first time doing a reproducible example - I've used dput on the head of the file but please let me know if there is a way I could have done this more clearly or better).

structure(list(V1 = c("St George's", "Sheffield", "Plymouth", 
"Exeter", "King's College London", "East Anglia"), 
Sample = c(183L, 139L, 106L, 128L, 152L, 178L), 
Total = c(417L, 342L, 350L, 520L, 659L, 875L), 
Response = c(43.9, 40.6, 30.3, 24.6, 23.1, 20.3), 
Lat = c(51.427194, 53.380941, 50.415735, 50.737137, 51.511486, 52.621921), 
Long = c(-0.174503, -1.487947, -4.110571, -3.535147, -0.115997, 1.239176)), 
.Names = c("V1", "Sample", "Total", "Response", "Lat", "Long"), 
row.names = c(NA, 6L), class = "data.frame")

Once I've got the datafile loaded, I do this:

UK <- map_data(map = "world", region = "UK")

ggplot(data = UK, aes(x = long, y = lat, group = group)) +
  geom_polygon() +
  geom_point(data = unidata, aes(x = Long, y = Lat, size = Response, col = "red")) +
  coord_map()

However, this gets me the following error:

Error in eval(expr, envir, enclos) : object 'group' not found

There is a group in the UK data, and when I run this code without the geom_point line, I get a standard map of the UK, so I assume the error is in this line. However, it doesn't seem that geom_point requires group. So I must be overlooking something?

like image 940
Jaccar Avatar asked Apr 11 '26 21:04

Jaccar


1 Answers

It works when you move the arguments describing which dataframe and columns to use to the geom_polygon() element. Running the following code, you get the desired plot:

ggplot() +
  geom_polygon(data = UK, aes(x = long, y = lat, group = group)) +
  geom_point(data = unidata, aes(x = Long, y = Lat, size = Response), col = "red") +
  coord_map()

I've also moved the col = "red" argument outside of the aes() brackets so it doesn't show up in your legend.

like image 63
A. Stam Avatar answered Apr 14 '26 11:04

A. Stam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!