ggplot2 - how to keep the legend items with the same size, when geom_segment() has different sizes?

29 Views Asked by At

I'm plotting several segments as once using ggplot2, with two different sizes.

An example of what I want to do is provided in one of the answers here. Here's the example they provide:

ggplot2::ggplot() +
  geom_segment(data = df[df$type=="A", ], aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 12)+
  geom_segment(data = df[df$type=="B", ], aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 6)

The output being:

enter image description here

My question is: how can I make the legend items have the same size? As provided in the answer I mention on the post, but I don't know how it turned out like this:

enter image description here

Any help or other suggestions are appreciated!

1

There are 1 best solutions below

2
Jon Spring On BEST ANSWER
ggplot(data = df) +
  geom_segment(aes(colour = type, x = x1, xend = x2, y = id, yend = id, size = type)) +
  scale_size_manual(values = c("A" = 12, "B" = 6)) +
  guides(size = "none", color = guide_legend(override.aes = list(linewidth = 6)))

enter image description here

where

df <- data.frame(id = c("id1", "id1", "id2", "id2"), 
                 x1 = c(10, 9, 12, 12 ), x2 = c(16, 17, 15, 19),
                 type = c("A", "B", "A", "B"))