Adam_G
Adam_G

Reputation: 7879

Display line type correctly in ggplot legend

I have the following data frame and plot. In the plot's legend, the point's shapes are not displayed and the lines are too thick. Is there a way to fix this?

library(ggplot2)
library(ggalt)

x <- rnorm(100)
y <- rnorm(100)
group <- rep(c("A","B","C","D"), 25)
dat <- data.frame(x,y,group)

ggplot(dat, aes(x=x, y=y, shape=group, color=group)) +
  geom_point() +
  geom_encircle(data=subset(dat, group=='A'), aes(x=x,y=y),size=2, linetype=2) +
  geom_encircle(data=subset(dat, group=='B'), aes(x=x,y=y), size=3, linetype=3) +
  geom_encircle(data=subset(dat, group=='C'), aes(x=x,y=y),size=4, linetype=4) +
  geom_encircle(data=subset(dat, group=='D'), aes(x=x,y=y))

enter image description here

Upvotes: 3

Views: 2996

Answers (1)

zlipp
zlipp

Reputation: 801

Rather than play with sizing all in the same legend, it might be easiest to split out your shape and line type into different legends. Not exactly what you were looking for, but I think it looks good.


library(ggplot2)
library(ggalt)

x <- rnorm(100)
y <- rnorm(100)
group <- rep(c("A","B","C","D"), 25)
dat <- data.frame(x,y,group)

ggplot(dat, aes(x=x, y=y, shape=group, color=group)) + 
  geom_point() +
  geom_encircle(aes(size=group, linetype = group)) + 
  scale_size_manual(values=c("A" = 2, "B" = 3, "C" = 4, "D" = 1)) +
  scale_shape_discrete(name = 'Shapes') +
  scale_color_discrete(name = 'Linetypes') +
  scale_linetype_discrete(name = 'Linetypes') +
  guides(shape = guide_legend(override.aes = list(size = 3)),
         linetype = guide_legend(override.aes = list(shape = NA)),
         size = FALSE) +
  theme(legend.key.size = unit(1, 'cm'),
        legend.box = 'horizontal')

Upvotes: 2

Related Questions