我试图在同一个图上绘制3个因子的2D直方图,但我无法使其工作。绘制直方图但由于某种原因,第二因子的颜色出现在第三因子的第二直方图上,而相反。另外,无论我尝试过什么,只有2个对象的图例出现在最终图表上。任何想法???
这是我的代码
library(ggplot2)
library(grid)
library(gtable)
# plot with red fill
AmAs <-read.csv("AmAs.csv", header = TRUE)
p1 <- ggplot(data = AmAs, aes(x, y, color = as.factor(Group))) +
stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
scale_fill_continuous(low = "grey", high = "red", space = "Lab",name="And")+
scale_colour_discrete(guide = FALSE) +
theme_classic()
# plot with blue fill
p2 <- ggplot(data = AmAs, aes(x, y, color = as.factor(Group))) +
stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
scale_fill_continuous(low = "grey", high = "blue",space="Lab",name="Gyn") +
scale_colour_discrete(guide = FALSE) +
theme_classic()
# plot with orange fill
p3 <- ggplot(data = AmAs, aes(x, y, color = as.factor(Group))) +
stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
scale_fill_continuous(low="grey",high="orange",space="Lab", name = "Fer") +
scale_colour_discrete(guide = FALSE) +
theme_classic()
# grab plot data
pp1 <- ggplot_build(p1)
pp2 <- ggplot_build(p2)$data[[1]]
pp3<- ggplot_build(p3)$data[[1]]
# replace red fill colours in pp1 with blue colours from pp2 when group is 2
pp1$data[[1]]$fill[grep(pattern="^2",pp2$group)]<-pp2$fill[grep(pattern="^2", pp2$group)]
pp1$data[[1]]$fill[grep(pattern = "^3", pp3$group)] <- pp3$fill[grep(pattern = "^3", pp3$group)]
# build plot grobs
grob1 <- ggplot_gtable(pp1)
grob2 <- ggplotGrob(p2)
grob3 <- ggplotGrob(p3)
# build legend grobs
leg1 <- gtable_filter(grob1, "guide-box")
leg2 <- gtable_filter(grob2, "guide-box")
leg3 <- gtable_filter(grob3, "guide-box")
leg <- gtable:::rbind_gtable(leg1[["grobs"]][[1]], leg2[["grobs"]][[1]], "first")
# replace legend in 'red' plot
grob1$grobs[grob1$layout$name == "guide-box"][[1]] <- leg
# plot
grid.newpage()
grid.draw(grob1)