简体   繁体   中英

R ggplot: Plot variables in 3 categories

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)

在此处输入图片说明

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM