2017-10-10 257 views
0

我想为我的情节添加一个新的图例。但我希望传奇都是定制的。 我通过geom_text_repel为每个点添加标签。 新的图例描述了标签的字符。如何将自定义图例添加到用ggplot绘图?

Before

After

+0

你为什么不使用'GEOM_LABEL()'的标签? – djhurio

+0

我对R和ggplot2不太了解。我将检查geom_label()。 – Clifford

回答

0

您可以通过创建“虚拟”的数据包含了传说键标签创建一个传奇。然后,您将“绘制”虚拟数据以生成图例,但使用空白符号以便实际上没有任何绘图。

library(ggplot2) 
theme_set(theme_classic())  

# Fake data for plotting 
set.seed(2) 
val = sapply(sample(1:4,30,replace=TRUE), function(x) paste(sort(sample(c('c','u','x','t'), x)), collapse="")) 
dat = data.frame(x=runif(30), y=runif(30), val) 

# Dummy data for creating the legend 
leg = data.frame(x1=rep(0,4), y1=rep(0,4), ll = c("c: coor","u: url","x: xss","t: text")) 

ggplot(data=dat, aes(x,y)) + 
    geom_text(aes(label=val)) + 
    geom_point(data=leg, aes(x1, y1, colour=ll)) + 
    theme(legend.key.size=unit(15,"pt"), 
     legend.title=element_blank(), 
     legend.margin=margin(l=0), 
     legend.text=element_text(size=12)) + 
    scale_colour_manual(values=rep("#00000000", 4)) 

enter image description here

你也可以使用geom_text直接将 “传奇” 的注释:

leg = data.frame(ll = sort(c("c: coor","u: url","x: xss","t: text"))) 
leg$y = seq(mean(dat$y) + 0.05*diff(range(dat$y)), 
      mean(dat$y) - 0.05*diff(range(dat$y)), 
      length=4) 
leg$x = 1.07 * max(dat$x) 

ggplot(data=dat, aes(x,y)) + 
    geom_text(aes(label=val)) + 
    geom_text(dat=leg, aes(label=ll), hjust=0, colour="red") + 
    annotate(xmin=1.05 * max(dat$x), xmax=1.18 * max(dat$x), ymin=0.95*min(leg$y), ymax=1.04*max(leg$y), 
      geom="rect", fill=NA, colour="black") + 
    scale_x_continuous(limits=c(min(dat$x), 1.18*max(dat$x))) 

enter image description here

+0

它的工作原理。非常感谢你。但是可以避免情节中文字标签之间的重叠吗? – Clifford

相关问题