R:ggplot2让geom_文本的字符正好覆盖一个X单位

R:ggplot2让geom_文本的字符正好覆盖一个X单位,r,ggplot2,text,R,Ggplot2,Text,我想根据字符串中的位置突出显示文本,例如,如果我们有以下文本: this is a really nice informative piece of text 然后我想说,让我们围绕位置2到4画一个矩形: t[his] is a really nice informative piece of text 我尝试在ggplot2中使用以下代码执行此操作: library(ggplot2) library(dplyr) box.data <- data.frame( start

我想根据字符串中的位置突出显示文本,例如,如果我们有以下文本:

this is a really nice informative piece of text
然后我想说,让我们围绕位置2到4画一个矩形:

t[his] is a really nice informative piece of text
我尝试在ggplot2中使用以下代码执行此操作:

library(ggplot2)
library(dplyr)

box.data <- data.frame(
  start   = c(4,6,5,7,10,7),
  type    = c('BOX1.start', 'BOX1.start', 'BOX1.start','BOX1.end', 'BOX1.end', 'BOX1.end'),
  text.id = c(1,2,3,1,2,3)
)

text.data <- data.frame(
  x = rep(1,3),
  text.id = c(1,2,3),
  text = c('Thisissomerandomrandomrandomrandomtext1',
           'Thisissomerandomrandomrandomrandomtext2',
           'Thisissomerandomrandomrandomrandomtext3')
)


ggplot(data = text.data, aes(x = x, y = text.id)) + 
  scale_x_continuous(limits = c(1, nchar(as.character(text.data$text[1])))) +
  geom_text(label = text.data$text, hjust = 0, size = 3) +
  geom_line(data = box.data, aes(x = start, y = text.id, group = text.id, size = 3, alpha = 0.5, colour = 'red'))
库(ggplot2)
图书馆(dplyr)

box.data我刚刚发现我可以将字符串拆分成字符并打印出来,也许这对其他人有用

library(ggplot2)
library(dplyr)
library(splitstackshape)

# First remember the plotting window, which equals the text length
text.size = nchar(as.character(text.data$text[1]))

# Split the string into single characters, and adjust the X-position to the string position
text.data <- cSplit(text.data, 'text', sep = '', direction = 'long', stripWhite = FALSE) %>%
  group_by(text.id) %>%
  mutate(x1 = seq(1,n()))

# Plot each character and add highlights 
ggplot(data = text.data, aes(x = x1, y = text.id)) + 
  scale_x_continuous(limits = c(1, text.size)) +
  geom_text(aes(x = text.data$x1, y = text.data$text.id,  group = text.id, label = text)) +
  geom_line(data = box.data, aes(x = start, y = text.id, group = text.id, size = 3, alpha = 0.5, colour = 'red'))
库(ggplot2)
图书馆(dplyr)
库(splitstackshape)
#首先记住打印窗口,它等于文本长度
text.size=nchar(如.character(text.data$text[1]))
#将字符串拆分为单个字符,并将X位置调整为字符串位置
text.data%
分组依据(text.id)%>%
突变(x1=seq(1,n())
#绘制每个角色并添加高光
ggplot(数据=text.data,aes(x=x1,y=text.id))+
比例x连续(极限=c(1,文本大小))+
geom_text(aes(x=text.data$x1,y=text.data$text.id,group=text.id,label=text))+
geom_线(数据=box.data,aes(x=start,y=text.id,group=text.id,size=3,alpha=0.5,颜色为“红色”))
生成此绘图的对象:

也许标记应该向上和向下延伸一点,但这是一个容易修复的问题