我正在使用ggplot2开发一个图形,其中我需要将文本叠加在其他图形元素上。根据文本底层的颜色,可能难以阅读文本。有没有办法在具有半透明背景的边框中绘制geom_text?
我可以用plotrix做这个:
library(plotrix) Labels <- c("Alabama","Alaska","Arizona","Arkansas") SampleFrame <- data.frame(X = 1:10,Y = 1:10) TextFrame <- data.frame(X = 4:7,Y = 4:7,LAB = Labels) ### plotrix ### plot(SampleFrame,pch = 20,cex = 20) Boxed.labels(TextFrame$X,TextFrame$Y,TextFrame$LAB,bg = "#ffffff99",border = FALSE,xpad = 3/2,ypad = 3/2)
但是我不知道用ggplot2获得类似结果的方法:
### ggplot2 ### library(ggplot2) Plot <- ggplot(data = SampleFrame,aes(x = X,y = Y)) + geom_point(size = 20) Plot <- Plot + geom_text(data = TextFrame,y = Y,label = LAB)) print(Plot)
正如你所看到的,黑色的文本标签是不可能感知到它们在背景中与黑色geom_points重叠的位置。
解决方法
尝试这个geom,这是从GeomText稍微修改。
GeomText2 <- proto(GeomText,{ objname <- "text2" draw <- function(.,data,scales,coordinates,...,parse = FALSE,expand = 1.2,bgcol = "grey50",bgfill = NA,bgalpha = 1) { lab <- data$label if (parse) { lab <- parse(text = lab) } with(coordinates$transform(data,scales),{ tg <- do.call("mapply",c(function(...) { tg <- with(list(...),textGrob(lab,default.units="native",rot=angle,gp=gpar(fontsize=size * .pt))) list(w = grobWidth(tg),h = grobHeight(tg)) },data)) gList(rectGrob(x,y,width = do.call(unit.c,tg["w",]) * expand,height = do.call(unit.c,tg["h",gp = gpar(col = alpha(bgcol,bgalpha),fill = alpha(bgfill,bgalpha))),.super$draw(.,parse)) }) } }) geom_text2 <- GeomText2$build_accessor() Labels <- c("Alabama",LAB = Labels) Plot <- ggplot(data = SampleFrame,y = Y)) + geom_point(size = 20) Plot <- Plot + geom_text2(data = TextFrame,label = LAB),size = 5,expand = 1.5,bgcol = "green",bgfill = "skyblue",bgalpha = 0.8) print(Plot)
BUG固定和代码改进
GeomText2 <- proto(GeomText,bgalpha = 1) { lab <- data$label if (parse) { lab <- parse(text = lab) } with(coordinates$transform(data,{ sizes <- llply(1:nrow(data),function(i) with(data[i,],{ grobs <- textGrob(lab[i],gp=gpar(fontsize=size * .pt)) list(w = grobWidth(grobs),h = grobHeight(grobs)) })) gList(rectGrob(x,lapply(sizes,"[[","w")) * expand,"h")) * expand,parse)) }) } }) geom_text2 <- GeomText2$build_accessor()