I am trying to create a simple scatterplot in ggplot2 that has a unique shape for each factor level but certain colours are the same. I can achieve this, but would like a nicer looking legend where I can group the different symbols with the same colour together with a single label. So in the example data below, I would like the legend to show the three green symbols (circle, square, diamond) followed by "Control", then the two orange (triangle) symbols followed by "Restored" and then the purple symbol followed by "Reference":
library(ggplot2)
df <- data.frame(V1 = rnorm(60,0,1), V2 = rnorm(60,1,2),
Site = factor(rep(c("Site A","Site B","Site C","Site D", "Site E","Site F"), each =10)),
Xtra_Info = c(rep("Control",times=30),rep("Restored",times=20),rep("Reference",times=10)))
##Rename the labels that I want to appear in the legend
levels(df$Site) <- list(`Site A` = "Site A",`Site B` = "Site B",Control = "Site C",
`Site D` = "Site D", Restored = "Site E", Reference= "Site F")
ggplot() +
geom_point(data=df,aes(x=V1,y=V2,fill=Site,shape=Site),size=4) +theme_bw()+
scale_fill_manual(values = c("#1b9e77","#1b9e77","#1b9e77", "#d95f02","#d95f02", "#7570b3"),
guide = guide_legend(nrow = 1))+
scale_shape_manual(values = c(21:25,21)) +
theme(legend.position = "top",legend.title=element_blank(),
legend.text = element_text(face="bold",size=12),legend.spacing.x = unit(0.3, 'cm'))
I've asked a similar question before (Sharing multiple ggplot legend symbols with one label) that has worked for stacked bar charts, but doesn't seem to be working for scatterplot in ggplot2. Any information would be much appreciated, thanks.
The same approach of course works also for your scatter plot:
library(ggplot2)
labels <- levels(df$Site)
labels[c(1, 2, 4)] <- ""
ggplot() +
geom_point(data = df, aes(x = V1, y = V2, fill = Site, shape = Site), size = 4) +
theme_bw() +
scale_fill_manual(
labels = labels,
values = c("#1b9e77", "#1b9e77", "#1b9e77", "#d95f02", "#d95f02", "#7570b3"),
guide = guide_legend(nrow = 1)
) +
scale_shape_manual(
labels = labels,
values = c(21:25, 21),
guide = guide_legend(nrow = 1)
) +
theme(
legend.position = "top", legend.title = element_blank(),
legend.text = element_text(face = "bold", size = 12), legend.spacing.x = unit(0.3, "cm")
)