Search code examples
rggplot2scalefacet-grid

Creating a two-category graduated circle in ggplot2?


I have produced a graph where I have graduated circles to represent the number of birds in a location, but I would like to have a separate colour for each site.

Example of data:

datexample <- data.frame(
    "site" = c("A","B"), 
    "bird" = c("1A","2A"), 
    "season" = c("Fall","Winter"), 
    "lat" =  c(45.25, 44.75, 44.75, 44.75), 
    "lon" = c(-61.75), 
    "Count"=c(1,3,3,3)
)

datexample

Code for plot:

p = ggplot() +
  coord_sf(crs = 4326, xlim = c(-58, -69), ylim = c(40, 48))+
  xlab("Longitude")+
  ylab("Latitude")+
  facet_grid(. ~ season)+
  geom_point(data = datexample, aes(x = lon, y = lat, size=Count), pch=20, color="royalblue4")+
  scale_size_area()

p2 = p + theme(axis.text.x = element_text(angle = 90, hjust = 1))
p2

Output: enter image description here

Instead of having one colour for all points, I need a colour for each site, and for both of those to appear in the legend.

I'm new to R, so any help would be appreciated!


Solution

  • You can add this guides(color = guide_legend("Site", override.aes = list(size = 5))) to your code to change the size of the dots in the legend

    library(tidyverse)
    theme_set(theme_minimal(base_size = 14))
    
    p = ggplot() +
      coord_sf(crs = 4326, xlim = c(-58, -69), ylim = c(40, 48))+
      xlab("Longitude")+
      ylab("Latitude")+
      facet_grid(. ~ season)+
      geom_point(data = datexample, aes(x = lon, y = lat, 
                                        size = Count,
                                        color = site), pch = 20)+
      scale_size_area()
    
    p2 <- p + 
      theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
      guides(color = guide_legend("Site", override.aes = list(size = 5)))
    p2
    

    Created on 2019-03-02 by the reprex package (v0.2.1.9000)