Skip to content

Using a linear gradient as fill aestheticΒ #6351

@jbengler

Description

@jbengler

Hi Teun!

I am tinkering around with this plot using an alpha-gradient as fill.

library(ggplot2)
library(grid)

df <- data.frame(
  year = 2011:2020,
  value = c(10,9,7,6,9,10,12,11,14,15)
)

my_gradient_alpha <- function(color = "red", max_alpha = 1, start_point = 0) {
  linearGradient(
    c(NA, alpha(color, max_alpha)),
    c(start_point, 1),
    x1 = unit(0, "npc"), y1 = unit(0, "npc"),
    x2 = unit(0, "npc"), y2 = unit(1, "npc")
  )
}

df |>
  ggplot(aes(year, value)) +
  geom_area(fill = my_gradient_alpha(max_alpha = 0.5)) +
  geom_line(linewidth = 1, color = "red") +
  theme_minimal()
Image

Now, I would like to generalize this to work with the fill aesthetic.

library(ggplot2)
library(grid)

df2 <- data.frame(
  year = 2011:2020,
  value = c(10,9,7,6,9,10,12,11,14,15,
            4,5,6,4,3,4,6,7,9,10),
  id = rep(c("id1","id2"), each = 10)
)

df2 |>
  ggplot(aes(year, value, fill = id, color = id, group = id)) +
  geom_area(alpha = 0.4, position = "identity") +
  geom_line(linewidth = 1) +
  theme_minimal()

I tried this but it does not work.

df2 |>
  ggplot(aes(year, value, fill = id, color = id, group = id)) +
  geom_area(aes(
    fill = after_scale(my_gradient_alpha(color = colour, max_alpha = 0.5))
    ),
    position = "identity") +
  geom_line(linewidth = 1) +
  theme_minimal()

Is there a way to do this in current ggplot2? If not, do you see a way to implement this?

Best
Jan

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions