1

Is there any way of having the alpha value vary across an area chart in R ggplot?

Example

I'd like to vary the alpha across x so that it's dark on the right and light on the left.

I'd also be interested in having the alpha value be based on the y value, so it's darkest at the peak and lightest at the trough.

Any ideas?

Here's my code:

library(ggplot2)

x <- 1:1000
y <- sin(2*pi*x/1000 + 4)*25 + 45

df <- data.frame(x, y)

df$month <- rep("", times = nrow(df))

months <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", 
"Dec")

for (i in 1:nrow(df)){
   ind <- floor(i/83.33334) + 1
   print(ind)
   df$names[i] <- months[ind]
}

df$names <- factor(df$names, levels = months)

p <- ggplot(df, aes(x = x, y = y, fill = "red"))+
  geom_area(position = "identity", aes(alpha = x/1000))+
  theme_minimal() + 
  theme(legend.position = "none")+
  scale_alpha_continuous(guide=FALSE)

p

EDIT: Crucially, unlike other questions that this question is (not even remotely) similar to, I am interested in responses specifically for geom_area style ggplots.

It is important that this question stay open so that those with the same question as myself know workarounds, using geom_segment, or know that what is being asked is not possible within ggplot. So whoever closed my question can just bloody well open it again and stop gate-keeping this site.

FURTHER EDIT: This question now has a whole new answer that is not in the supposed "duplicates" which is to use geom_col. Works a treat. The people deserve to know! Un-close this question!

Leonhard Euler
  • 231
  • 1
  • 7
  • 2
    Here's a [few](https://stackoverflow.com/questions/33965018/ggplot-how-to-produce-a-gradient-fill-within-a-geom-polygon) [related](https://stackoverflow.com/questions/48210231/creating-a-vertical-color-gradient-for-a-geom-bar-plot/48235903#48235903) [questions](https://stackoverflow.com/questions/45677574/applying-a-gradient-fill-on-a-density-plot-in-ggplot2) – Gregor Thomas Mar 01 '23 at 15:13

1 Answers1

1

I would typically do this with vertical segments or columns. It's very easy if you have 1,000 contiguous x values as in your example:

ggplot(df, aes(x, y, alpha = x/1000))+
  geom_col(fill = "red", width = 1) +
  theme_minimal() + 
  scale_alpha_identity()

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • That looks pretty good. I'm getting some effects where some of the line segments are overlapping and it looks a bit stripy in places. Any advice to get rid? – Leonhard Euler Mar 01 '23 at 16:53
  • @LeonhardEuler yes, you could try columns with fill instead of lines with color - there shouldn't be any overlap that way. – Allan Cameron Mar 01 '23 at 17:31