0

I want to plot the following dataset:

data<-list()
data$Year<-c(rep(1995,4),rep(2005,4))
data$Name<-as.factor(c("name1","name2","name3","name4","name1","name2","name3","name4"))
data$species<-as.factor(c("cat","cat","dog","dog","cat","cat","dog","dog"))
data$Value<-c(1,2,3,4,5,6,7,8)
data<-as.data.frame(data)

This is my desired plot

p<-ggplot(data, aes(x=Year, y=Value,fill=Name, colour=Name,linetype=species,shape=species))
p<-p+geom_point()
p<-p+geom_line()

I want a different legend however. First, the legend should contain one entry for each 'name' with the correct symbol(color, linetype and shape). I can achieve this by doing the following (the linetypes do not exactly match, sorry):

#Plot with better legend
gg_color_hue <- function(n) {
  hues = seq(15, 375, length=n+1)
  hcl(h=hues, l=65, c=100)[1:n]
}
p2<-ggplot(data, aes(x=Year, y=Value,fill=Name, colour=Name,linetype=Name,shape=Name))
p2<-p2+scale_linetype_manual(values=c(1,1,2,2),breaks=levels(data$Name),name="test")
p2<-p2+scale_shape_manual(values=c(16,16,17,17),breaks=levels(data$Name),name="test")
p2<-p2+scale_colour_manual(values=gg_color_hue(4),breaks=levels(data$Name),name="test")
p2<-p2+scale_fill_manual(values=gg_color_hue(4),breaks=levels(data$Name),name="test")
p2<-p2+geom_point(show_guide=T)
p2<-p2+geom_line(show_guide=T)

Now however there is no distinction between cats and dogs anymore. Therefore I would like to have subtitles in the legend (or essentially two legends): Something like this:

cats
symbol(name1) name1
symbol(name2) name2

dogs
symbol(name3) name3
symbol(name4) name4

Can somebody help me on this? Thank you.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453

1 Answers1

0

Didzis Elferts kindly pointed me to this thread where a solution using the package gridExtra is provided. This works in principle for me (see code below) but we already have our own set of libraries and unfortunately have some conflicting methods with the gridExtra package (getNames). Is there a way that does not rely on the gridExtra package?

Here the code for my example with gridExtra:

pcat<-ggplot(subset(data,species=="cat"), aes(x=Year, y=Value,fill=Name, colour=Name))+geom_point(shape=16)+geom_line(linetype=1)+guides(colour=guide_legend(title="cat"),shape=guide_legend(title="cat"),linetype=guide_legend(title="cat"),fill=guide_legend(title="cat"))
ppcat<-ggplot_gtable(ggplot_build(pcat))
legcat<-ppcat$grobs[[8]]

pdog<-ggplot(subset(data,species=="dog"), aes(x=Year, y=Value,fill=Name, colour=Name))+geom_point(shape=1)+geom_line(linetype=2)+guides(colour=guide_legend(title="dog"),shape=guide_legend(title="dog"),linetype=guide_legend(title="dog"),fill=guide_legend(title="dog"))
ppdog<-ggplot_gtable(ggplot_build(pdog))
legdog<-ppdog$grobs[[8]]

library(gridExtra)
grid.arrange(arrangeGrob(p,arrangeGrob(legcat,legdog),ncol=2,widths=c(4/5,1/5)))
Community
  • 1
  • 1