10

I'm working on plotting sf objects in ggplot2. I have a set of polygons buffered that have a density value for each polygon density. I want to plot this along with a single sf point GPS_point as a reference point. The problem I am running into is that I cannot set the fill color separately for each object.

ggplot() +
  geom_sf(data = buffered, aes(fill = density),lwd = 0) + #polygons filled based on the density value
  geom_sf(data = GPS_point, aes(fill = "red"), size = 5) + #reference point that I want to make red
  scale_fill_viridis_c(option = "magma",begin = 0.1)

I am trying to set the reference point fill color to red. The current code sets the fill for both objects as magma. The problem is that this makes the reference point indistinguishable from the background because they end up as the same color. Is there any way to manipulate the fill color separately for these two geom_sf calls?

David
  • 195
  • 1
  • 1
  • 10
  • 2
    when you put the fill inside of `aes()` it will treat it as a variable and use your color palette. To get your desired outcome, remove simply put `fill = 'red'` outside of the aesthetic. – Chris May 17 '19 at 18:14
  • 1
    I gave that a go, but it is still displaying the color as black (which is the 0 value for the `magma` color palette) – David May 17 '19 at 18:39
  • 7
    ah, I overlooked the fact that the correct parameter for point data is `col` or `colour` and not `fill` ! – Chris May 17 '19 at 20:06
  • That worked. Thanks! – David May 17 '19 at 23:02
  • 1
    @zx8754 have done now, thanks – Chris Jun 13 '23 at 20:41
  • 1
    @Chris with 18K views in 4 years, you missed out on many upvotes :) – zx8754 Jun 13 '23 at 20:44

1 Answers1

2

The correct syntax for passing a hardcoded colour to a geom is to put it outside of the aes:

ggplot() +
  geom_sf(data = buffered, aes(fill = density),lwd = 0) + #polygons filled based on the density value
  geom_sf(data = GPS_point, fill = "red", size = 5) + #reference point that I want to make red
  scale_fill_viridis_c(option = "magma",begin = 0.1)

The difference is that aes expects a variable (as you pass 'density' in the first geom_sf call), which it will use to graduate the fill depending on the value that variable takes. Hardcoded colours eg 'red' should be passed without an aes

Chris
  • 3,836
  • 1
  • 16
  • 34