问题描述
这是我的尝试
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")
我试图添加一个图例,该图例具有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
,可以这样实现:
-
可以通过
guide_legend
为图例设置样式,该图例使您可以覆盖默认aes来指定每个图例键的shape
和size
-
可以通过主题选项
legend.position
和legend.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))))