Skip to content

Unusual behavior in the legend #6728

@Breeze-Hu

Description

@Breeze-Hu

Hi, Teun!

I recalled this previous issue while attempting to generate gradient fills. You provided relevant code. However, the code in ggplot 4.0 has undergone some changes in the legend section, though the main plot remains fine.

Is this a bug or an adjustment to the mechanism for drawing legends?

Yeah the my_gradient_alpha() should be vectorised and return a list of gradients parallel to color for this to work out.

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)
)

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

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()

Created on 2025-03-03 with reprex v2.1.1

Originally posted by @teunbrand in #6351


NOW:

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)
)

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

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()

Created on 2025-11-05 with reprex v2.1.1

Setting show.legend = FALSE will cause the gradient in the legend to disappear.

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)),
  ),
  show.legend = FALSE,
  position = "identity") +
  geom_line(linewidth = 1) +
  theme_minimal()
Image

Best wishes,
Hu

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