0

I'd like to make a geom_area plot with the fill colour based on the y (or any other) value, similar to the geom_density_ridges_gradient function of the ggridges package. I could achieve this with multiple geom_cols but I want to have the nice smooth geom_area style. Do you have any idea?

This code illustrates what I want to do:

data <- data.frame(x = 1:100,
                   y = rnorm(100, 20,3))


#I'd like to have an area plot with the fill colour based on the y values
ggplot(data = data, aes(x = x, y = y))+
  geom_area(aes(fill = y))

#As in a bar plot, but with a smooth area, not a composite of rectangles
ggplot(data = data, aes(x = x, y = y))+
  geom_col(aes(fill = y))

Thanks a lot!

OnLeRo
  • 83
  • 1
  • 6
  • I think you want to provide the _contour_ of the `geom_area` but with the left-to-right color changes of `geom_col` (without the inter-bar spacing), is that right? Isn't that more of a left-to-right gradient? – r2evans Feb 19 '23 at 21:18
  • Said differently, what about the `geom_col` plot needs to be changed: space between columns; change from boxy-tops to a peak-to-peak line; anything else? – r2evans Feb 19 '23 at 21:20
  • @r2evans Yes, I'd like to have the `geom_col` plot with the contour of the `geom_area`, i.e. a "smooth" contour and not rectangles. And yes, also no gaps between the bars, so I'd set `width = 1`. – OnLeRo Feb 19 '23 at 22:16

1 Answers1

1

You can use approx to get a huge number of interpolated values and plot them as very thin vertical geom_segments

data2 <- as.data.frame(approx(data$x, data$y, seq(1, 100, len = 5000)))

ggplot(data = data2, aes(x = x, y = y))+
  geom_segment(aes(xend = x, yend = 0, colour = y), linewidth = 0.1) +
  geom_area(fill = NA, color = "black") +
  scale_color_viridis_c() +
  theme_minimal(base_size = 20)

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87