【问题标题】:How to add legend to geom_point PCA plot?如何将图例添加到 geom_point PCA 图?
【发布时间】:2020-04-21 16:07:26
【问题描述】:

我已经制作了一个 PCA 图,但我正在努力如何在其中获得一个图例(对 R 来说很新)

这是代码,包括颜色的向量。

pca_cols <- c("seagreen3","seagreen3","seagreen3","seagreen3","seagreen3","seagreen3","steelblue","steelblue","steelblue","steelblue")

ggplot(datascores12, aes(x=PC1, y=PC2))+
  geom_point(size=3,fill=pca_cols, shape = 21)+
  xlab(paste("PC1 ", "(",data_exp12[1],"%)", sep=""))+
  ylab(paste("PC2 ", "(",data_exp12[2],"%)", sep=""))+
  theme(axis.title.y = element_text(face = "bold"),
             legend.text = element_text(face = "bold"),
             axis.text.x = element_text(face = "bold"),
             axis.text.y = element_text(face = "bold"),
             axis.title.x = element_text(face = "bold"),
             legend.title = element_text(face = "bold"),
             panel.grid.major = element_line(size = 0.25, linetype = 'dashed',
                                             colour = "grey"),
             panel.grid.minor = element_line(size = 0.25, linetype = 'dashed',
                                             colour = "grey"),
             panel.background = element_blank(),
             axis.line = element_line(colour = "black"),
             plot.title = element_text(face = "bold", size = 10, hjust = 0.5))+
  theme(legend.position = "bottom", legend.title = element_blank())

制作这个情节:

enter image description here

我想在底部加个图例,切不明白!

提前致谢

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    为了让您看到图例,您需要将该参数包含在 aes() 内的图例中。因此,将geom_point 行更改为:

    geom_point(size=3,fill=pca_cols, shape = 21)
    

    忠告:让ggplot 决定如何根据数据集中的变量为数据点应用美感会更容易且更好。举个简单的例子:

    # dummy dataset
    df <- data.frame(
            x=sample(1:20,20),
            y=rnorm(20,1,0.1),
            group=c('A', 'B')
        )
    
    # color specifications
    cols <- list('A'='red', 'B'='blue')
    
    # plot
    ggplot(df, aes(x,y)) +
        geom_point(aes(fill=group), shape=21, size=3) +
        theme_bw() +
        scale_fill_manual(values = cols)
    

    ggplot 根据位置和编码为因子的数据帧中的变量“组”决定如何填充每个点。

    【讨论】:

    • 谢谢!我不知道会发生这种情况
    • 是的,如果您的原始数据框包含赋予颜色含义的列,您可以在数据集中执行类似的操作。如果您将这些组的名称分配给列表中的特定颜色,就像我使用的示例一样,它将使分配特定颜色变得容易。或者,您可以设置美感,让ggplot 提出配色方案并自动完成所有操作,它仍然看起来很漂亮并且清晰。
    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多