GigaZaur
GigaZaur

Reputation: 47

ggplot2: Set custom color, shape, and size for points added to a map

I want to set custom shape, size and color for points added to a map based upon a variable called 'Dataset'. I'm able to set the color of the points if I set the shape to the same type for all the points, but I'm hoping to have a map with a little more information. When I runt this code, all the points are circles colored black. What am I missing?

Thanks everyone for your help & time!!

Here's a reproducible example:

    # Read in libraries
    library(ggplot2)
    library(maps)
    library(maptools)
    library(ggmap)

    # Create mapping objects
    world <- map_data("world2")
    world$long <- world$long
    state_dat <- map_data("state")
    canada <- world[world$region==c("Canada"),]
    map_dat <- rbind(state_dat, canada)

    # Create custom shapes, sizes, colors
    pt_colors=c("red", "blue", "grey", "green")
    shapes = c(120, 22, 24, 21)
    shape_size = c(1.1, 0.8, 1, 1)

    # Create lat/long dataframe
    xy <- data.frame(Dataset=c("GBIF","Flower","GBIF","Leaf","DNA","GBIF","GBIF","Leaf","GBIF","GBIF","DNA","GBIF","DNA","GBIF","GBIF","Leaf","GBIF","GBIF","GBIF","DNA"),
                      lat=c(38.89450,34.45300,39.86556,30.38818,28.74590,33.78527,41.23439,30.37935,41.38250,40.60648,30.87580,40.56425,28.75000,41.52666,35.46451,30.73621,38.50221,33.70335,38.98000,29.61100),
                      long=c(-77.06292,-84.22643,-79.50248,-84.64519,-81.47860,-84.37109,-81.46374,-86.17667,-72.10861,-74.53538,-84.41520,-74.86654,-81.47750,-73.15833,-78.89952,-86.73095,-78.40308,-86.70289,-77.03917,-81.78740)
    )

    # Create base map
    p0 <- ggplot() +
      geom_polygon(data=map_dat,aes(x=long,y=lat,group=group, fill=region),fill="white",color="black", show.legend=FALSE)+
      coord_map("gilbert",xlim=c(-60,-97),ylim=c(15,47.5)) +#mollweide is pretty good
      labs(x=expression("Longitude"*~degree*W), y=expression("Latitude"*~degree*N)) +
      theme(panel.border = element_rect(colour = "black", fill=NA, size=1),
        plot.margin=unit(c(0.25,0.25,0.25,0.25),'inches'),
        legend.position='none') +
      theme(rect = element_blank())

    # Add points to the map
    p1 <- p0 +
        geom_point(data=xy,aes(x=long,y=lat,fill=Dataset)) + 
        scale_color_manual(values=pt_colors) + 
        scale_shape_manual(values=shapes) + 
        scale_size_manual(values=shape_size)

Plot

Upvotes: 1

Views: 4226

Answers (1)

dshkol
dshkol

Reputation: 1228

You need to have colour, shape, and size within your geom_point aesthetic values. Geom_point doesn't use fill as an aesthetic, but uses colour.

Simply fixing that will generate what you want.

p1 <- p0 +
  geom_point(data=xy,aes(x=long,y=lat,colour = Dataset, shape = Dataset, size = Dataset)) + 
  scale_color_manual(values=pt_colors) + 
  scale_shape_manual(values=shapes) + 
  scale_size_manual(values=shape_size)

Upvotes: 6

Related Questions