0

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.

Electrino
  • 2,636
  • 3
  • 18
  • 40
  • 2
    Can you give an example of how you want "to change the alpha value"? All lines at alpha 0.5? Alpha varying with radius (along with color)? Alpha varying based on another variable? – Jon Spring Apr 13 '23 at 19:06

1 Answers1

2

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

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Interesting answer. I want to hardcode/embed the alpha value. I was wondering how I could do this if each circle had a unique colour. for example, changing `color = letters[1:9]` in my code above will create 9 circles with individual colours. How could I use adjustcolor in this case? – Electrino Apr 13 '23 at 19:24
  • To confirm, you mean hardcode one alpha value for all colors? – Jon Spring Apr 13 '23 at 19:26
  • 3
    For that, you could try something like `color = stage(letters[1:9], after_scale = alpha(color, 0.5))` – Seth Apr 13 '23 at 19:27
  • Excellent, I was indeed hardcoding a single alpha value for all colours. Using the stage/after_scale did the trick. thanks! – Electrino Apr 13 '23 at 21:31