rggforce

How to change colour of geom_circle border in R?


I am creating a plot that draws circles using ggforce::geom_circle and I'm trying to change the alpha value for the lines. It seems that geom_circle has an alpha argument that affects the fill of the circle, but not the outline.

For example:

library(ggforce)
library(ggplot2)

circles <- data.frame(
  x0 = rep(1:3, 3),
  y0 = rep(1:3, each = 3),
  r = seq(0.1, 1, length.out = 9)
)


# Use coord_fixed to ensure true circularity
ggplot() +
  geom_circle(aes(x0 = x0, y0 = y0, r = r, color = r), data = circles) +
  coord_fixed()

The code produces several circles, Im just trying to change the alpha value of the circle lines, but I cant seem to figure out a way to do it.


Solution

  • As @Seth helpfully suggests, this is an ideal case to use stage/after_scale to adjust the colors in the last step before they are plotted. If you have a my_col variable in your data, this will work whether that variable is continuous or discrete.

    ... + 
    geom_circle(aes(x0 = x0, y0 = y0, r = r, 
                color = stage(my_col, after_scale = alpha(color, 0.3))),
                data = circles) + ...
    

    enter image description here

    Alternatively, if you are using a continuous scale and want a varying alpha along it, you could encode alpha into one of the colors in that gradient. In the case below, I add 00, ie alpha 0, to the high end color of the scale, starting from the default colors in scale_color_gradient (they're specified in the help file). This relies on how hex values in R can be encoded either as #RRGGBB or #RRGGBBAA if you want to give them an embedded alpha. You could also use adjustcolor or rgb as explained here: Transparent equivalent of given color

    ggplot() +
      geom_circle(aes(x0 = x0, y0 = y0, r = r, color = r), data = circles) +
      scale_color_gradient(low  = "#132B43",
                           high = "#56B1F700") +
      coord_fixed()
    

    enter image description here