如何在具有多个geom_point图层的图中为图例设置样式和位置?

问题描述

这是我的尝试

  ggplot() + 
  geom_point(data = standard_expression_TS.kmeans.df,aes(A,B,color = "DF1")) +
  geom_point( data = experimental_expression_TS.kmeans.df,color = "DF2"),shape = 1,alpha = 0.8) +
  geom_point(data = as.data.frame(standard_expression_TS.kmeans$centers),color='DF3'),shape=4,size=8) + 
  labs(title="Expression Scatterplot") + theme(plot.title = element_text(hjust = 0.5)) +
  scale_colour_manual(values=c("DF1"="black","DF2"="blue","DF3"="red"),name="Genes")

这就是我的情节的样子:

enter image description here

我试图添加一个图例,该图例具有3种点类型(黑点,蓝色圆圈,红色x),后跟字符串(“ DF1”,“ DF2”,“ DF3”)。如果可能的话,我希望将其放在地上,并与左下角齐平。

注意:我正在寻找一种避免将所有数据融合在一起的方法。

编辑:当我更改“ DF1-3”的名称时,它将停止工作。

ggplot() + 
  geom_jitter(data = mtcars,aes(hp,mpg,color = "Standard")) +
  geom_jitter(data = mtcars,color = "Experimental"),alpha = 0.8) +
  geom_jitter(data = mtcars,color='Center'),size=8) + 
  labs(title="Expression Scatterplot") + 
  theme(plot.title = element_text(hjust = 0.5),legend.position = c(0,0),legend.justification = c("left","bottom")) +
  scale_colour_manual(values=c("Standard"="black","Experimental"="blue","Center"="red"),name="Genes") +
  guides(color = guide_legend(override.aes = list(shape = c(16,1,4),size = c(1.5,1.5,8))))

解决方法

使用mtcars作为示例数据集,并使用geom_jitter代替geom_point,可以这样实现:

  1. 可以通过guide_legend为图例设置样式,该图例使您可以覆盖默认aes来指定每个图例键的shapesize

  2. 可以通过主题选项legend.positionlegend.justification来实现图例的位置。 legend.justification设置图例的x和y轴锚点,而legend.position(介于0和1之间)设置相对于这些锚点的位置。

library(ggplot2)

ggplot() + 
  geom_jitter(data = mtcars,aes(hp,mpg,color = "DF1")) +
  geom_jitter(data = mtcars,color = "DF2"),shape = 1,alpha = 0.8) +
  geom_jitter(data = mtcars,color='DF3'),shape=4,size=8) + 
  labs(title="Expression Scatterplot") + 
  theme(plot.title = element_text(hjust = 0.5),legend.position = c(0,0),legend.justification = c("left","bottom")) +
  scale_colour_manual(values=c("DF1"="black","DF2"="blue","DF3"="red"),name="Genes") +
  guides(color = guide_legend(override.aes = list(shape = c(16,1,4),size = c(1.5,1.5,8))))

更改图例中标签的最简单方法是通过labels中的scale_color_manual进行设置:

library(ggplot2)

ggplot() + 
  geom_jitter(data = mtcars,"bottom")) +
  scale_colour_manual(values = c(DF1 = "black",DF2 = "blue",DF3 = "red"),labels = c(DF1 = "Standard",DF2 = "Experimental",DF3 = "Center"),name = "Genes") +
  guides(color = guide_legend(override.aes = list(shape = c(16,8))))

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...