ggplot合并了图例

时间:2017-09-01 08:50:03

标签: plot ggplot2 aes

我遇到类似的问题:How to merge color, line style and shape legends in ggplot

我想从虹膜数据集中绘制物种以及我执行的聚类。为简单起见,我们假设聚类由

给出
c(rep(1,45),rep(2,59),rep(3,46)))

不知何故,上面引用的帖子中的建议对我不起作用

library(ggplot2)
library(scales)

ggplot(iris, aes(Petal.Length, Petal.Width, color = Species)) +
geom_point(shape = 18, size = 7) + 
geom_point(shape = 15, size = 3,data = iris, 
    aes(iris$Petal.Length, iris$Petal.Width, 
        color = as.factor(c(rep(1,45),rep(2,59),rep(3,46))))) + 
scale_color_manual(values=rep(alpha(c("#00B6EB","#F8766D",  "#53B400"),0.5),2)) + 
scale_shape_manual("",values=c(18,18,18,15,15,15))

在图例中,我想要为物种1,2,3和形状18(钻石)的形状15(方框)。

enter image description here

1 个答案:

答案 0 :(得分:2)

这是一个非常不优雅的解决方案:

library(ggplot2)
library(scales)
iris$clust <- factor(c(rep(1,45),rep(2,59),rep(3,46)))

p <- ggplot(iris, aes(Petal.Length, Petal.Width, color = Species))+
geom_point(shape=18, size=7) + 
geom_point(shape=15, size=3, data=iris, 
           aes(iris$Petal.Length, iris$Petal.Width, color=clust)) + 
scale_color_manual(values=rep(alpha(c("#00B6EB","#F8766D",  "#53B400"),0.5),2))+ 
scale_shape_manual("",values=c(18,18,18,15,15,15))

# Generate a ggplot2 plot grob
g <- ggplotGrob(p)

# Set the color of unwanted shapes in legend to background color 
g$grobs[[15]][[1]][[1]][[1]][[4]]$gp$col <- NA
g$grobs[[15]][[1]][[1]][[1]][[7]]$gp$col <- NA
g$grobs[[15]][[1]][[1]][[1]][[10]]$gp$col <- NA

g$grobs[[15]][[1]][[1]][[1]][[14]]$gp$col <- NA
g$grobs[[15]][[1]][[1]][[1]][[17]]$gp$col <- NA
g$grobs[[15]][[1]][[1]][[1]][[20]]$gp$col <- NA

library(grid)
grid.draw(g)

enter image description here

相关问题