r – 带ggplot2的boxed geom_text

r – 带ggplot2的boxed geom_text,第1张

概述我正在使用ggplot2开发一个图形,其中我需要将文本叠加在其他图形元素上。根据文本底层的颜色,可能难以阅读文本。有没有办法在具有半透明背景的边框中绘制geom_text? 我可以用plotrix做这个: library(plotrix)Labels <- c("Alabama", "Alaska", "Arizona", "Arkansas")SampleFrame <- data.fram 我正在使用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()
总结

以上是内存溢出为你收集整理的r – 带ggplot2的boxed geom_text全部内容,希望文章能够帮你解决r – 带ggplot2的boxed geom_text所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1111163.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存