ggplot2图例显示异常:如何修复非圆形图例?
修复ggplot2中异常图例的问题
问题出在你的geom_text继承了全局的color = type映射,导致ggplot把文本元素也纳入了图例,所以图例里不是单纯的圆形点,而是点加文本的组合。
有两种简单的修复方式:
方式一:让geom_text不显示图例
给两个geom_text都加上show.legend = FALSE参数,明确告诉ggplot不要把文本元素放进图例:
control <- read.table(text = "genename fc p-val q-val type a 0.4 0.0034 0.031 con b 2 0.0005 0.01 con", header = T,sep="\t") treatment <- read.table(text = "genename fc p-val q-val type a 0.6 0.002 0.01 treat c 1.5 0.000066 0.004 treat", header =T, sep="\t") library(ggplot2) ggplot(control,aes(x = log2(fc), y = -log10(q.val), color = type))+ geom_point() + geom_text(data = subset(control, genename == "a"), aes(label = genename, vjust = 2), show.legend = FALSE) + # 添加这行 geom_point(data = treatment) + geom_text(data = subset(treatment, genename == "a"), aes(label = genename, vjust = 2), show.legend = FALSE) + # 添加这行 scale_color_manual(values = c("con" = "blue", "treat" = "red"))
方式二:把颜色映射仅绑定给geom_point
把color = type从全局的ggplot() aes里移到geom_point的aes中,这样只有点会使用颜色映射,文本不会继承这个映射,也就不会干扰图例:
control <- read.table(text = "genename fc p-val q-val type a 0.4 0.0034 0.031 con b 2 0.0005 0.01 con", header = T,sep="\t") treatment <- read.table(text = "genename fc p-val q-val type a 0.6 0.002 0.01 treat c 1.5 0.000066 0.004 treat", header =T, sep="\t") library(ggplot2) ggplot(control,aes(x = log2(fc), y = -log10(q.val)))+ # 移除全局color映射 geom_point(aes(color = type)) + # 把color映射移到这里 geom_text(data = subset(control, genename == "a"), aes(label = genename, vjust = 2)) + geom_point(data = treatment, aes(color = type)) + # 这里也要加上color映射 geom_text(data = subset(treatment, genename == "a"), aes(label = genename, vjust = 2)) + scale_color_manual(values = c("con" = "blue", "treat" = "red"))
两种方法都能让图例恢复成单纯的圆形点,你可以根据自己的习惯选择。
内容的提问来源于stack exchange,提问作者user3138373
相关产品推荐
相关产品推荐

