[英]How to add a custom legend to plot with ggplot?
我想在我的情節中添加一個新的圖例。 但我希望傳奇都是定制的。 我通過 geom_text_repel 為每個點添加標簽。 新圖例描述了標簽的特性。
您可以通過創建包含圖例鍵標簽的“虛擬”數據來創建圖例。 然后,您將“繪制”虛擬數據以生成圖例,但使用空白符號,以便實際繪制任何內容。
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))
您還可以使用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.