Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display line type correctly in ggplot legend

Tags:

r

ggplot2

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

like image 260
Adam_G Avatar asked Dec 31 '25 10:12

Adam_G


1 Answers

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')

like image 111
zlipp Avatar answered Jan 03 '26 02:01

zlipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!