Skip to content

Easier way to add manual legend #6386

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
brunomioto opened this issue Apr 1, 2025 · 1 comment
Open

Easier way to add manual legend #6386

brunomioto opened this issue Apr 1, 2025 · 1 comment

Comments

@brunomioto
Copy link

When I was trying to remake this plot:

Image

It's quite hard to create these legends as we are already using fill and color.

I know there some options, but I was thinking in a easier way. Something like:

df |> 
  ggplot(aes(x = value, y = categories))+
  geom_col()+
  add_legend(fill = "#d8d8d8", color = NA, name = "Dentro das terras indígenas")+
  add_legend(fill = NA, color = "#222222", name = "Fora das terras indígenas")

Could it be added to ggplot2, or to other package like legendry?

@teunbrand
Copy link
Collaborator

Argueably, the distinguishing feature between the two sets of filled/open bars is the linetype.
If you divide the these sets over two layers, the legend for linetype already distinguishes filled/non-filled along with the linetype.

library(ggplot2)

df <- data.frame(
  x = c(-2, -1, 2, 1), 
  y = c(1, 2, 1, 2),
  g = c(1, 1, 2, 2)
  )

ggplot(df, aes(x, y, linetype = factor(g))) +
  geom_col(
    data = ~ subset(.x, g == 1),
    orientation = 'y', colour = "black", fill = NA
  ) +
  geom_col(
    data = ~ subset(.x, g == 2),
    orientation = 'y'
  )

Created on 2025-04-01 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants