如何在 ggplot2 中为图例键混合不同的符号?

How to mix different symbols for legend keys in ggplot2?

我有以下生成图形的代码。

cols <- brewer.pal(n = 3, name = 'Dark2')

p4 <- ggplot(all.m, aes(x=xval, y=yval, colour = Approach, ymax = 0.95)) + theme_bw() + 
  geom_errorbar(aes(ymin= yval - se, ymax = yval + se), width=5, position=pd) + 
  geom_line(position=pd) + geom_point(position=pd) + 
  geom_hline(aes(yintercept = cp.best$slope, colour = "C2P"), show_guide = FALSE) + 
  scale_color_manual(name="Appraoch", breaks=c("C2P", "P2P", "CP2P"), values =  cols[c(1,3,2)]) + 
  scale_y_continuous(breaks = seq(0.4, 0.95, 0.05), "Test AUROC") +
  scale_x_continuous(breaks = seq(10, 150, by = 20), "# Number of Patient Samples in Training")

p4 <- p4 + theme(legend.direction = 'horizontal', 
      legend.position = 'top', 
      plot.margin = unit(c(5.1, 7, 4.5, 3.5)/2, "lines"), 
      text = element_text(size=15), axis.title.x=element_text(vjust=-1.5), axis.title.y=element_text(vjust=2))   
p4

如何将符号更改为仅 "C2P" 的图例中没有点的线,而不影响 "P2P" 和 "CP2P" 的符号?

您可以使用 override.aes 从图例中删除点标记,方法是将以下代码行添加到您的绘图中:

guides(colour=guide_legend(override.aes=list(shape=c(NA,16,16))))

override.aes 更改图例而不更改情节。在这种情况下,我们要更改图例点标记,因此我们要更改点的 shape。 16 号点标记是一个实心圆(参见 ?pch),我们希望为两个标记保留它,但我们使用 NA 删除图例中第一个项目的点标记。