I'm doing a plot in ggplot that has three layers-a polygon layer, and two points layers. The points layers each use different data sets that I cannot combine easily. I can get the plot itself to render like I want, but I am struggling with the legend. I need two legends: one for the polygon colors, and one for the points. The polygon legend should only show a color, and the points legend should show color and shape in a single legend. Everything is plotting OK, but I am getting black points over top of the fill in the polygon legend, and I am not getting shapes in the points legend. Reprex below:
library(ggplot2)
ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
values <- data.frame(
id = ids,
value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5)
)
positions <- data.frame(
id = rep(ids, each = 4),
x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)
datapoly <- merge(values, positions, by = c("id"))
datapoly$fruit <- 'apple'
datapoly$fruit[1:12] <- 'orange'
datapoints <- data.frame(x=datapoly$x+1, y=datapoly$y+1)
datapoints$drink <- NA
datapoints$clothing <- NA
datapoints$drink[1:12] <- 'drink'
datapoints$clothing[13:24] <- 'clothing'
drinkpoints <- datapoints[1:12, 1:3]
clothingpoints <- datapoints[13:24, c(1,2,4)]
cols <- c('black', 'steelblue')
polygon_cols <- c('red', 'grey50')
shp <- c(3,19)
ggplot()+
geom_polygon(data=datapoly, aes(x=x, y=y, fill=fruit))+
geom_point(data=drinkpoints,
aes(x=x, y=y,color=drink), alpha=0.75, shape=19,
show.legend = TRUE)+
geom_point(data=clothingpoints, aes(x=x, y=y,color=clothing),shape=3,
alpha=0.75, show.legend = FALSE)+
scale_color_manual(values= cols,
aesthetics = 'color',
name= 'Shop Type',
guide= guide_legend(override.aes = list(size=3,alpha=1)))+
scale_color_manual(values= polygon_cols,
aesthetics = 'fill',
name= 'Fruit Growing Area',
guide= 'legend')+
scale_shape_manual(values = shp,
name= 'Shop Type',
guide= guide_legend(override.aes = list(size=3, alpha=1)))
Created on 2020-12-03 by the reprex package (v0.3.0)