Skip to content

FR: Add dimension labels in guide_legend_cross() #79

@DanChaltiel

Description

@DanChaltiel

Hi,

Here is an idea on specific, yet common cases: crossed comparisons.

For instance, one could imagine a plot for a diagnosis test, with matching cases being plain while non-matching cases being dimmed.
The plot would have 2 colors (positive/negative) and 2 alphas (matching/ non-matching).
However, the default alpha legend is not very intuitive, and it would be much better IMHO if it could be "crossed".

An example is worth a thousand words, so here is a clumsy one using patchwork:

library(tidyverse)
library(patchwork)
set.seed(0)

df = expand.grid(x=1:5, tag1 = c("+", "-"), tag2=c("+", "-")) %>% 
  mutate(y = runif(n()))

p = df %>% 
  ggplot() +
  aes(x = x, y = y, fill=tag1, group=tag1, alpha=tag1==tag2) +
  geom_col(position = 'dodge', show.legend=FALSE) +
  scale_alpha_manual(values=c(0.5, 1))

legend = df %>% 
  distinct(tag1, tag2) %>% 
  ggplot() +
  aes(x = fct_rev(tag1), y = tag2, fill=fct_rev(tag1), group=tag1, alpha=tag1==tag2) +
  geom_tile(width=0.9, height=0.9, show.legend=FALSE) +
  scale_alpha_manual(values=c(0.5, 1)) + 
  scale_x_discrete(position = "top") +
  coord_equal() +
  labs(x="Disease", y="Test") +
  theme_minimal()
  
wrap_plots(p, legend, widths=c(6,1))

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

Image

I have no idea how to implement that from inside ggplot2, but I'd be amazed by a legendry feature that would allow something like:

p +
  guides(
    fill = guide_2d_custom(by=alpha)
  ) 

Would this be a reasonable feature request?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions