Search code examples
rggplot2mapsgeom-point

geom_point colors not correct using ggplot2


I'm stumped as to why my points are incorrectly coloured. I have set my own colour palette and used this to define the colours of the geom_point() but the colours that are actually being plotted are incorrect.

colfunc <- colorRampPalette(c("black", "#FFAFAF"))
plot(rep(1,41), col=colfunc(41), pch=19, cex=3)

cols <- colfunc(41)

df$cols <- cols[df$num]

baseMap <- ggplot(data = world) +
  geom_sf(color = "black", fill = "grey") +
  geom_point(data = df, 
             mapping = aes(x = lon, y = lat, col = cols[num])) +
  xlab("Longitude") + ylab("Latitude")

baseMap

The colour palette I have created looks like this:

Colour palette

But this is resulting in the following colours:

Resulting colours

Why aren't these colours matching??

Thanks

I have tried numerous different ways of setting the aes() but can't work out why the colours don't match


Solution

  • You need scale_colour_manual() or similar. We do not have your df. This is an example based on another df:

    library(ggplot2)
    colfunc <- colorRampPalette(c("black", "#FFAFAF"))
    # plot(rep(1,41), col=colfunc(41), pch=19, cex=3)
    cols <- colfunc(41)
    world <-ggplot2::map_data(map = "world")
    
    set.seed(1)
    df <- data.frame(lon = runif(41, min(world$long), max(world$long)),
                     lat = runif(41, min(world$lat), max(world$lat)), 
                     id = 1:41, cols = cols)
    
    ggplot(world, aes(x = long, y = lat)) + 
      geom_polygon(aes(group = group), colour = "grey") +
      geom_point(data = df, 
                 mapping = aes(x = lon, y = lat, 
                               colour = factor(id))) +
      scale_colour_manual(values = df$cols) +
      xlab("Longitude") + ylab("Latitude")
    

    Created on 2023-11-18 with reprex v2.0.2