How to add multiple titles in legend ggplot?
library(RColorBrewer)
library(ggplot2)
data1<-data.frame(x= rnorm(20, 0,1),
y=rnorm(20, 1,1),
section=c("a1", "a2", "a3", "a4", "a5", "a6", "a7",
"a8", "a9","a10","b1", "b2", "c1", "c2", "c3",
"d1", "d2", "e1", "e2","f1"),
region=c(rep("a",10), rep("b",2),rep("c",3),rep("d",2),
rep("e",2), rep("f",1))) #data
newpalette<-c(colorRampPalette(brewer.pal(9,"Blues"))(15)[15:6],
brewer.pal(9,"Greens")[c(4,8)],
brewer.pal(9,"Oranges")[c(4,7,9)],
brewer.pal(9,"Purples")[c(4,8)],
brewer.pal(9,"BrBG")[c(1,3)],
brewer.pal(9,"Greys")[5]) #20 color values
labels<-c("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9","a10",
"b1", "b2",
"c1", "c2", "c3",
"d1", "d2",
"e1", "e2",
"f1")
data1$section<-factor(data1$section,levels= labels)
p.legend<-ggplot( ) +
geom_point(data=data1, aes(x, y, colour = section,
shape=section), size=2)+
scale_color_manual(values =newpalette ,labels= labels)+
scale_shape_manual(values =
c(rep(1,10),0,0,2,2,2,3,3,5,5,6),labels= labels)
I want the region values as the subtitles in legend like following figure.
Mayebe we could modify spacing of some specific legend keys (e.g. legend key a10, c3). And then use grid.text
adding the text (a, b, c...) into the spacing like How to add multiple legend titles (columns) in ggplot. But my subtitiles are more complex and I don't know how to modify spacing of some specific legend keys.
Or we could create some another values (e.g. a11) and make it lucency in legend. Then adding the text b into the a11 spacing.But I don't know how to remove the specific legend keys and texts.
The third ways, I had ever add \n\n
into some labels codes to create the spacing.
labels2<- c("a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9","a10\n\n",
"b1", "b2",
"c1", "c2", "c3\n\n",
"d1", "d2\n\n",
"e1", "e2\n\n",
"f1")
p.legend<-ggplot( ) +
geom_point(data=data1, aes(x, y, colour = section,
shape=section), size=2)+
scale_color_manual(values =newpalette ,labels= labels2)+
scale_shape_manual(values =
c(rep(1,10),0,0,2,2,2,3,3,5,5,6),labels= labels2)
But the labels and key would not align like following figure
These are three ways that I had tried and failed.