简体   繁体   English

如何添加自定义图例以使用 ggplot 进行绘图?

[英]How to add a custom legend to plot with ggplot?

I want to add a new legend to my plot.我想在我的情节中添加一个新的图例。 But I hope the legend is all customized.但我希望传奇都是定制的。 I add the label for every point by geom_text_repel.我通过 geom_text_repel 为每个点添加标签。 The new legend describes the of character of the labels.新图例描述了标签的特性。

前

后

You can create a legend by creating "dummy" data that contains the legend key labels.您可以通过创建包含图例键标签的“虚拟”数据来创建图例。 You would then "plot" the dummy data in order to generate the legend, but use blank symbols so that nothing actually gets plotted.然后,您将“绘制”虚拟数据以生成图例,但使用空白符号,以便实际绘制任何内容。

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))

在此处输入图片说明

You could also use geom_text to place the "legend" annotations directly:您还可以使用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)))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM