ggplot合并图例中两个重叠图的形状

ggplot合并图例中两个重叠图的形状,plot,ggplot2,aes,Plot,Ggplot2,Aes,我有一个类似于这里提出的问题: 我想从iris数据集中绘制物种,并进行聚类。为了简单起见,让我们假设 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_po

我有一个类似于这里提出的问题:

我想从iris数据集中绘制物种,并进行聚类。为了简单起见,让我们假设

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的形状为15(方框),物种的形状为18(钻石)


这里有一个非常不雅观的解决方案:

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)
库(ggplot2)
图书馆(比例尺)

iris$clust谢谢你的帖子,这肯定有效。为什么一个更简单的解决方案(见我的帖子和引用的帖子)不起作用?