Skip to content

Problem with shared legends when using different geoms and linetypes mixed with colors #247

@dvalenciaca

Description

@dvalenciaca

I have 4 plots, each with a different geom, but share the same legend. To group the plots, I use patchwork, but this time I haven't been able to make the legend the way I would like it, as the Sample elements repeat. Any idea?

library(ggplot2)
library(patchwork)

Sample <- c("a", "b")
Time <- c(0,1,2)

df <- expand.grid(Time=Time, Sample = Sample)
df$Value <- c(1,2,3,2,4,6)

p1 <- ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_point(aes(color = Sample)) +
  geom_line(aes(color = Sample))

p2 <- ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_function(fun = function(x) x,
                aes(linetype = "Class 1",
                    color = "Class 1")) +
  geom_function(fun = function(x) 2*x,
                aes(linetype = "Class 2",
                    color = "Class 2")) +
  scale_color_manual(name = "Class",
                     values = c("red", "blue")) +
  scale_linetype_manual(name = "Class",
                        values = c(1,2))

p3 <- ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_point(aes(color = Sample))

p4 <- ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_point(aes(color = Sample))

plots <- ((p1/p2)|(p3/p4)) +
  plot_annotation(tag_levels = "a") +
  plot_layout(guides = "collect")
plots

image

I would like to remove some of the sample from the legend

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