Reputation: 85
I am using the CO2 dataset in R, and I would like to plot uptake and conc as x and y values, categorised by shape and fill, specified as Treatment and Plant, respectively. In addition, I would like to further categorise the space of the plot using the geom_polygon Type category.
I can perform fill and shape, and geom_polygon individually, but cannot find a way to combine all these parameters together in a single plot. The only way I was able to do this so far has been using annotation (rect) to create a box representing Type. Here is my code to reproduce the plots.
library(ggplot2)
library(plyr)
data.set <- as.data.frame(CO2)
####1st plot
ggplot(data.set, aes(x=as.numeric(uptake),
y=as.numeric(conc),
fill=Plant,
shape=Treatment))+
geom_point(size=2, stroke=1)+
geom_point(aes(color=Plant),size=1)+
scale_shape_manual(values = c(21, 22))
find_hull <- function(df) df[chull(df$uptake, df$conc), ]
hulls <- ddply(data.set, "Type", find_hull)
####2nd plot
ggplot(data = data.set, aes(x=as.numeric(uptake),
y=as.numeric(conc),
fill=Type,
colour=Type))+
geom_point() +
geom_polygon(data = hulls, alpha = 0.5)
Upvotes: 0
Views: 536
Reputation: 2056
You just need to move your the shape and color aesthetics from the ggplot to the specific geom layers:
ggplot(data.set, aes(x=as.numeric(uptake), y=as.numeric(conc))) +
geom_polygon(data = hulls, alpha = 0.5, aes(fill = Type)) +
geom_point(size = 2, stroke = 1, aes(shape = Treatment)) +
geom_point(aes(color = Plant,shape = Treatment), size = 1) +
scale_shape_manual(values = c(21, 22))
Upvotes: 1