6

I have a shapefile, my_sf. If I write:

ggplot() +
  geom_sf(
    data = my_sf,
    size = 0.5 # this is the default value actually
  )

then it works just fine. However, if I add a my_line_width attribute to my_sf, and set each value in that column to 0.5, and then write:

ggplot() +
  geom_sf(
    data = my_sf,
    aes(size = my_line_width)
  )

then I get a bunch of massive lines that overlap hideously. If the normal lines are width 0.5, then these are perhaps width 4. I don't understand why those don't produce the same result (aside from the legend, which I know only pops up if you use an aesthetic). Does anyone know what's going on?

I have also tried using lwd instead of size. Exactly the same thing happens: it's fine when I just set a static value, but when I try to provide values through an aesthetic, it goes wrong.

Michael Roswell
  • 1,300
  • 12
  • 31
JohnDoeVsJoeSchmoe
  • 671
  • 2
  • 8
  • 25

2 Answers2

8

I'm pretty sure this has to do with the idea behind aes mapping the data to the plot. For example, see Difference between passing options in aes() and outside of it in ggplot2 or When does the aesthetic go inside or outside aes()?. Use size or whatever inside aes to map data to the aesthetic in whatever way ggplot will understand it (more on that below) or outside aes with a constant value to actually get ggplot to use that value. The behavior you are finding is true with ggplot generally and not specific to geom_sf.

You can see that this is true for size even with geom_point

mtcars %>% ggplot(aes(mpg, wt, size=cyl))+geom_point()
k<-4
mtcars %>% ggplot(aes(mpg, wt, size=k))+geom_point()
k<-6
mtcars %>% ggplot(aes(mpg, wt, size=k))+geom_point()
k<-10
mtcars %>% ggplot(aes(mpg, wt, size=k))+geom_point()  

Also, the default treatment of size is pretty confusing with ggplot2, IMO: Does point area not increase linearly with size with scale_size_continuous?. When only provided 1 value inside aes, the line thickness will probably always be the baseline default size. As your commenter noted, you can adjust this behavior with scale, and you can use "identity" to some extent but it may be helpful to provide a range https://stackoverflow.com/a/11570926/8400969.

Michael Roswell
  • 1,300
  • 12
  • 31
2

As I overlooked the comments (this one and this one):

In ggplot version 3.4 linewidth was introduced!!

https://www.tidyverse.org/blog/2022/11/ggplot2-3-4-0/#hello-linewidth

benjazehr
  • 145
  • 1
  • 7