Search code examples
rggplot2scale

Plotting quantity of teachers per county on a map in R


I have two data sets MASS and MASS2 to create a map in R. I got the first one with the help of library(ggmap).

counties<-map_data('county')
MASS<-map_data('county', 'massachusetts')

 str(MASS)
 data.frame':   744 obs. of  6 variables:
 $ long       : num  -70.7 -70.5 -70.5 -70.5 -70.5 ...
 $ lat        : num  41.7 41.8 41.8 41.8 41.8 ...
 $ group      : num  1 1 1 1 1 1 1 1 1 1 ...
 $ state      : chr  "massachusetts" "massachusetts" "massachusetts"  ...
 $ county_name: chr  "barnstable" "barnstable" "barnstable" "barnstable" ...

The second consists of 14 points one per each county and has a teacher's quantity data per that county.

 str(MASS2)
'data.frame':   14 obs. of  6 variables:
 $ state        : chr  "massachusetts" "massachusetts" "massachusetts" ...
 $ county_name  : chr  "barnstable" "berkshire" "bristol" "dukes" ...
 $ long         : num  -70.7 -73.5 -71.2 -70.5 -71 ...
 $ lat          : num  41.7 42 41.7 41.4 42.4 ...
 $ group        : num  1 2 3 4 5 6 7 8 9 10 ...
 $ teacher_count: int  62 40 47  ...

I need to create a map where each teacher_count point will be represented by a circle in accordance with teacher's amount. So far I'm getting just one size circles.

My code is next:

 ggplot(MASS, aes(long,lat, group = group)) +
 geom_polygon(aes(fill = county_name),colour = "black") +
 geom_point(data = MASS2, aes(x = long, y = lat), color = "red", size = 5)+
 theme(legend.position="none") +
 coord_quickmap()

This is the map I get

I found one solution online which offers to represent the size in geom_point as

 +geom_point(......, size = MASS2$teacher_count*circle_scale_amt)+
  scale_size_continuous(range=range(MA$teacher_count)) 

but R can't find circle_scale_amt.

I am a new to R and trying to learn. Will appreciate ideas for any other ways to represent the teachers by their quantity! Thank you!


Solution

  • This works for me after setting a value for circle_scale_amt to rescale the size of the points otherwise they would be too big.

    library(ggmap)
    
    counties <- map_data('county')
    MASS <- map_data('county', 'massachusetts')
    
    circle_scale_amt <- 0.05
    
    ggplot(MASS, aes(long,lat, group = group)) +
      geom_polygon(aes(fill = subregion),colour = "black") +
      geom_point(data = MASS2, aes(x = long, y = lat), 
                 size = MASS2$teacher_count * circle_scale_amt,
                 color = "red", alpha = 0.6)+
      scale_size_continuous(range = range(MASS2$teacher_count)) +
      theme(legend.position="none") +
      coord_quickmap()
    

    Created on 2018-03-16 by the reprex package (v0.2.0).